using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace UDP
{
public partial class Form1 : Form
{
private bool IsHandle = true;
private UdpClient udp;
private int length = 0;
public Form1()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
ReceiveMsg();
}
private void ReceiveMsg()
{
udp = new UdpClient(26666, AddressFamily.InterNetwork);
Thread thread = new Thread(HandleUdpMsg);
thread.IsBackground = true;
IsHandle = true;
thread.Start();
}
private void HandleUdpMsg()
{
while (IsHandle)
{
IPEndPoint endPoint = null;
byte[] buffer = udp.Receive(ref endPoint);
string content = Encoding.UTF8.GetString(buffer);
chatContentText.AppendText(endPoint.Address + ":\n\t" + content + "\n");
length += buffer.Length;
label3.Text = "共计收到\t" + length + "\tbyte";
}
udp.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
IsHandle = false;
}
private void MsgSendBtn_Click(object sender, EventArgs e)
{
string text = sendMsgText.Text;
if (string.IsNullOrEmpty(text))
{
return;
}
IPAddress ip = IPAddress.Parse("172.16.20.237");
int port = 26666;
IPEndPoint remote = new IPEndPoint(ip, port);
UdpClient udp = new UdpClient();
udp.Connect(remote);
byte[] bytes = Encoding.UTF8.GetBytes(text);
int sendLength = udp.Send(bytes, bytes.Length);
SendResult.Text = "已向\t" + ip.ToString() + "\t发送\t" + sendLength + "\t字节。";
chatContentText.AppendText("我:\n\t" + text + "\n");
sendMsgText.Clear();
udp.Close();
}
}
}
但是可以接受得到。