C# wm6通过udp协议和pc通讯
2010-08-22 12:45:00 来源:WEB开发网}
catch
{
//退出循环,结束线程
break;
}
}
}
/// 发送数据到远程主机
///
private void sendData()
{
UdpClient myUdpClient = new UdpClient();
IPAddress remoteIP=IPAddress.Parse(textBoxRemoteIP.Text);
if ( remoteIP== null)
{
MessageBox.Show("远程IP格式不正确");
return;
}
IPEndPoint iep = new IPEndPoint(remoteIP, port);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBoxSend.Text);
try
{
myUdpClient.Send(bytes, bytes.Length, iep);
myUdpClient.Close();
textBoxSend.Focus();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "发送失败");
}
finally
{
myUdpClient.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
udpClient.Close();
Application.Exit();
}
private void button2_Click(object sender, EventArgs e)
{
sendData();
}
private void Form1_Load(object sender, EventArgs e)
{
//获取本机第一个可用IP地址
IPAddress myIP = IPAddress.Parse("192.168.0.100");
//为了在同一台机器调试,此IP也作为默认远程IP
textBoxRemoteIP.Text = myIP.ToString();
//创建一个线程接收远程主机发来的信息
Thread myThread = new Thread(new ThreadStart(ReceiveData));
//将线程设为后台运行
myThread.IsBackground = true;
myThread.Start();
textBoxSend.Focus();
}
}
}
客户端就ok了。
下面我们写服务器端,代码和客户端基本一致,就不赘述了,服务器端设计界面如下:
更多精彩
赞助商链接