先看下实现效果:
基础知识参考:https://blog.youkuaiyun.com/subin_iecas/article/details/80289513
UDP是一个非连接的协议,传输数据之前源端和终端不建立连接,双方没有专有的通信通道。当发送端想传送数据时就简单地把数据扔到网络上,并不能保证他们能到达目的地。接收端由于没有与发送端建立专用的通信通道,因此接收数据时并不能确定是有谁发来的数据。
因此,在socket编程中UDP不需要进行连接,只要知道对方的IP和端口就能进行通信。UDP通信没有服务器和客户端之分,每台主机都是平等的。因此,进行通信的每个进程的代码是可以一模一样的。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace UDP_Host_B
{
public partial class Form1 : Form
{
private static Socket socket;
private static IPEndPoint port;
private static EndPoint remote_port;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btn_start_Click(object sender, EventArgs e)
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ip = IPAddress.Parse(tbox_local_IP.Text);
port = new IPEndPoint(ip, Convert.ToInt32(tbox_local_port.Text));
socket.Bind(port);
IPAddress remote_IP = IPAddress.Parse(tbox_remote_IP.Text);
remote_port = new IPEndPoint(remote_IP, Convert.ToInt32(tbox_remote_port.Text));
display_msg("启动聊天");
Thread th = new Thread(receive_msg);
th.IsBackground = true;
th.Start();
}
catch { }
}
void receive_msg()
{
while (true)
{
EndPoint received_port = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer = new byte[1024 * 1024 * 5];
int len = socket.ReceiveFrom(buffer, ref received_port); // 将接收消息的端口信息保存在第二个参数中
string msg = Encoding.UTF8.GetString(buffer, 0, len);
display_msg(remote_port.ToString() + ":" + msg);
}
}
void send_msg()
{
try
{
string msg = tbox_send.Text;
socket.SendTo(Encoding.UTF8.GetBytes(msg), remote_port);
display_msg("我" + ":" + msg);
tbox_send.Clear();
}
catch { }
}
private void btn_send_Click(object sender, EventArgs e)
{
send_msg();
}
private void tbox_send_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
send_msg();
}
}
void display_msg(string s)
{
tbox_display.AppendText(s + "\r\n");
}
}
}
将上述代码实例化两次,分配不同的端口,即可在同一台主机上通信;或者设置IP和端口在两台主机上通信。这里给出示例代码的具体工程,点击下载