UDP通信

最近做了一个网页的UDP通信的小东西,由于怕以后用到的时候找不到了,贴出来跟大家分享,代码也有好多是从网上找的

 1 //这里之所以用try catch是因为在接收的时候如果关闭窗口的话,会有一个进程挂起,导致再次运行的时候出错,这样写我也不知道有什么缺陷,希望懂的的人告诉一下 
 2 try
 3         {
 4             //建立一个新的UdpClient 6716是固定端口  不写则是随机端口
 5             udpClient = new UdpClient(6716);
 6             //连接远程服务器
 7             udpClient.Connect("192.168.2.25", 8080);
 8             RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("192.168.2.25"), 8080);
 9             //建立一个新的线程 以便后台运行
10             Thread t = new Thread(new ThreadStart(this.First));
11             t.Start();
12         }
13         catch (Exception)
14         {
15 
16         }      
17  protected void ReceiveData()
18     {
19 
20         string sql = "";
21         try
22         {
23             if (udpClient.Available >= 0)
24             {
25                 Byte[] receiveBytes;
26                 Thread.Sleep(700);
27                 try
28                 {
29                     //接收
30                     receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
31                     returnData = Encoding.ASCII.GetString(receiveBytes);
32                 }
33                 catch (Exception)
34                 {
35 
36                     return;
37                 }
38 
39                 if (returnData.Length == 35)
40                 {
41                     sql = "update Data set receiveData='" + returnData + "',receiveTime=getdate() where id =1";
42 
43                 }
44                 else if (returnData.Length == 83)
45                 {
46                     sql = "update Data set receiveData='" + returnData + "',receiveTime=getdate() where id =2";
47                 }
48                 else { }
49                 SQLHelper.ExecuteSql(sql);
50             }
51         }
52         catch (Exception)
53         {
54 
55             
56         }
57 
58         udpClient.Close();
59     }  

你可能感兴趣的:(UDP)