1.使用UDP的同步发送接收的方式,在本机上面实现数据的发生接收。
UdpClient udpClient = null;
UdpClient udpReceiver = null;
Thread receiveThread;
bool receiveThreadIsToRun=true;
public Form1()
{
InitializeComponent();
if (udpClient == null)
udpClient = new UdpClient(8112);
if (udpReceiver == null)
udpReceiver = new UdpClient(8110, AddressFamily.InterNetwork);
}
private void button2_Click(object sender, EventArgs e)
{
receiveThread = new Thread(new ThreadStart(receive));
receiveThread.Start();
}
private void receive()
{
while (receiveThreadIsToRun)
{
if (udpReceiver != null)
{
IPEndPoint remoteHost = null;
try
{
byte[] data = udpReceiver.Receive(ref remoteHost);
MessageBox.Show(Encoding.ASCII.GetString(data));
}
catch
{
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
byte[] bytes = Encoding.ASCII.GetBytes("create new");
udpClient.Send(bytes, bytes.Length, "127.0.0.1", 8110);
}
2.采用异步的方式来进行通信
AsyncCallback udpReceiverStartCallback;
UdpClient udpClient = null;
UdpClient udpReceiver = null;
public Form1()
{
InitializeComponent();
if (udpClient == null)
udpClient = new UdpClient(8112);
if (udpReceiver == null)
udpReceiver = new UdpClient(8110, AddressFamily.InterNetwork);
//异步
udpReceiverStartCallback = new AsyncCallback(updReceiverHander);
}
private void button1_Click(object sender, EventArgs e)
{
byte[] bytes = Encoding.ASCII.GetBytes("create new");
udpReceiver.BeginReceive(udpReceiverStartCallback, udpClient);
udpClient.Send(bytes, bytes.Length, "255.255.255.255", 8110);
}
private void updReceiverHander(IAsyncResult result)
{
if (result.IsCompleted)
{
IPEndPoint remoteHost = null;
byte[] data = udpReceiver.EndReceive(result, ref remoteHost);
MessageBox.Show(Encoding.ASCII.GetString(data) + "\r\n"+remoteHost.Address.ToString()+"\r\n"+remoteHost.Port.ToString());
}
}