UDP服务器
控件
两个按钮(打开服务器按钮,发送消息按钮),输入框,文本框控件(RichTextBox:显示聊天)
打开服务器按钮方法
创建全局变量 Socket
// 先讲socket进行客户端和服务器的书写
Socket socket;
private void button1_Click(object sender, EventArgs e)
{
//参数1 ip地址类型 ipv4的类型
//参数2 传递数据类型 数据报文类型
//参数3 协议类型 udp协议
//1 创建socket套接字作为服务器对象
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2绑定ip和端口
IPAddress iPAddress = IPAddress.Parse("192.168.107.83");
socket.Bind(new IPEndPoint(iPAddress,8081));
//3 接受消息
startReceive();
}
void startReceive()
{
//创建线程 开启线程
new Thread(() =>
{
byte[] body = new byte[1024];
while (true)
{
int count = socket.Receive(body); //接受数据
string s = Encoding.UTF8.GetString(body, 0, count);
richTextBox1.Invoke((Action)(() =>
{
richTextBox1.AppendText(s + "\t\n");
richTextBox1.SelectionStart=richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
}));
}
}).Start() ;
}
发送消息事件
//发消息的方法 给指定的人发消息
string[] ips = new string[] {"192.168.107.83", };
private void button2_Click(object sender, EventArgs e)
{
socket.SendTo(Encoding.UTF8.GetBytes(this.textBox1.Text),
new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8082)
);
}
UDP客户端
控件
三个按钮(打开,发送,关闭),RichTextBox(显示聊天)
public Form1()
{
InitializeComponent();
}
void f1()
{
byte[] body = new byte[1024];
while (true)
{
int count = socket.Receive(body); //接受数据
string s = Encoding.UTF8.GetString(body, 0, count);
richTextBox1.Invoke((Action)(() =>
{
richTextBox1.AppendText(s + "\t\n");
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
}));
}
}
// 打开连接
Socket socket;
private void button1_Click(object sender, EventArgs e)
{
try
{
//1创建客户端对象
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//bind 如果前后端写的端口一致的时候 出现错误,端口号只能使用一次
//2 绑定ip和端口号
socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8082));
Thread th = new Thread(f1);
th.Start();
}
catch (Exception ex)
{
MessageBox.Show("端口号被占用");
}
}
//发送消息
private void button2_Click(object sender, EventArgs e)
{
if (socket != null)
{
//参数1 发送的字符串转成字节数组
//参数2 发送数据的远程终端 new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8081)
socket.SendTo(Encoding.UTF8.GetBytes("倒反天罡"), new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8081));
}
}
//关闭
private void button3_Click(object sender, EventArgs e)
{
socket.Close();//关闭
socket = null;
}