PDA与PC基于Socket的同步
示例代码如下:
PDA端: string msg = "PDA_Ready";
private string SendMsgAndReciveMsg(string msg) { // 需要返回的字符串 string result = string.Empty; try { byte[] sendmsg = System.Text.Encoding.UTF8.GetBytes(msg); 需要发送的信息 System.Net.Sockets.TcpClient tcpc = new TcpClient(); System.Net.IPAddress ip = System.Net.IPAddress.Parse(this.hostIP); IP地址字符串转换在IP地址 System.Net.IPEndPoint ipendpoint = new System.Net.IPEndPoint(ip,this.port); 建立网络连接端点 tcpc.Connect(ipendpoint); tcpc.GetStream().Write(sendmsg,0,sendmsg.Length); 发送信息到PC int i = tcpc.GetStream().Read(request,0,request.Length);读取信息 result = Encoding.UTF8.GetString(request,0,i); tcpc.Close(); return result; } catch(Exception ex) { return result; } } PC端: 启动一个线程: private System.Net.Sockets.TcpListener tcpl; private System.Threading.Thread thread; thread=new Thread(new ThreadStart(SendReceive)); thread.Priority=System.Threading.ThreadPriority.AboveNormal; thread.Start(); 接收与发送 本文出自 51CTO.COM技术博客private void SendReceive() { try { ArrayList al=new ArrayList(); tcpl.Start(); this.statusBarPanel1.Text = "正在监听..."; while(lisen) { TcpClient tcpc = tcpl.AcceptTcpClient(); NetworkStream tcpStream = tcpc.GetStream(); byte[] request=new byte[6144]; int bytesRead = tcpStream.Read(request,0,request.Length); sbReceive = Encoding.UTF8.GetString(request,0,bytesRead); switch(sbReceive) { case "PDA_Ready": byte[] msg = Encoding.UTF8.GetBytes("Server_Ready"); tcpStream.Write(msg,0,msg.Length); break; } } |


clarke563
博客统计信息
热门文章
最新评论
友情链接
