服务端:
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
run();
}
private UdpClient server;
private IPEndPoint receivePoint;
private int port = 8080;//定义本机端口号
private int ip = 127001;//设置本机的IP
private Thread startServer;//定义线程
public void start_server()
{
while (true)
{
ASCIIEncoding encode = new ASCIIEncoding();
byte[] recData = server.Receive(ref receivePoint);
string Read_str = encode.GetString(recData);
this.listBox1.Items.Add(Read_str);
//
byte[] sendData = encode.GetBytes("1111");//将要回传回去的内容
server.Send(sendData, sendData.Length, receivePoint);
}
}
//创建一个线程
public void run()
{
//利用本地端口号来初始化一个UDP网络服务;
server = new UdpClient(port);
receivePoint = new IPEndPoint(new IPAddress(ip), port);
startServer = new Thread(new ThreadStart(start_server));
//启动线程
startServer.Start();
}
}
}
客户端[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private UdpClient client; //创建一个Udp网络服务
private int port = 8080; //定义端口号
private IPEndPoint receivePoint;
//发送数据函数
public void start_client()
{
client = new UdpClient(port);
receivePoint = new IPEndPoint(new IPAddress(127001), port);
IPAddress HostIp;
bool continueLoop = true;
while (continueLoop)
{
System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
//
string endString = this.textBox2.Text;//发送的字节赋值给endString
byte[] sendDate = encode.GetBytes(endString);//把endString代表的值转成8位数字格式
try
{
HostIp = IPAddress.Parse(textBox1.Text); //输入IP到textBox1;
IPEndPoint host = new IPEndPoint(HostIp, 8080); //要将数据文报发送到的主机IP和端口
client.Send(sendDate, sendDate.Length, host); //然后将UDP数据文报发送到远程主机
//sendDate=要发的字节;
//sendDate.Length=要发的字节的长度;
//host=发送到主机的端口号
byte[] recData = client.Receive(ref receivePoint); //返回已由远程主机发送的UPD数据文报;
this.textBox3.Text = encode.GetString(recData); //把返回的文报显示在textBox3中;
//
continueLoop = false;
}
catch (Exception)
{
client.Close();
return;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
start_client();
}
}
}
|