标签:style serialize odi ide global get ali 开发 需要
1、网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket。
1 //建立连接 客户端 2 Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 3 //这里的值我写在全局了,FM_JTApiUrl是IP,FM_JTDKH是端口号 4 clientSocket.Connect(Global.FM_JTApiUrl, Convert.ToInt32(Global.FM_JTDKH)); 5 //转json doorinfo是需要往端口发送的信息 6 string sendStr = JsonConvert.SerializeObject(doorinfo); 7 byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr); 8 //这里是往端口发数据 9 clientSocket.Send(sendBytes); 10 //返回的信息 12288为接收的信息大小,可自行改动 11 string recStr = ""; 12 byte[] recBytes = new byte[12288]; 13 int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0); 14 recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
3、服务端代码
1 //配置IP及端口 同上 2 IPAddress ip = IPAddress.Parse(Global.FM_ApiUrl); 3 IPEndPoint ipe = new IPEndPoint(ip, Convert.ToInt32(Global.FM_DKH)); 4 5 Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 6 sSocket.Bind(ipe); 7 //监听端口 8 sSocket.Listen(0); 9 //建立连接 10 Socket serverSocket = sSocket.Accept(); 11 12 string recStr = ""; 13 byte[] recByte = new byte[12288]; 14 int bytes = serverSocket.Receive(recByte, recByte.Length, 0); 15 recStr += Encoding.Default.GetString(recByte, 0, bytes);
注:发送或接收的时候最好写个日志,以方便以后查询bug
标签:style serialize odi ide global get ali 开发 需要
原文地址:https://www.cnblogs.com/MycnBlogs7854/p/10470330.html