注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 CCIE-Lab考试将新增10分钟..
 帮助

PDA与PC基于Socket的同步


2006-12-20 20:44:24
 标签: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();
接收与发送
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;
}
}




    文章评论
 
2008-02-18 14:37:03
while(lisen) 大哥这个lisen哪来的?

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: