Socket实现Udp的发送和接收
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _1Socket实现udp的发送
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket soc;
//打开
private void button1_Click(object sender, EventArgs e)
{
soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
soc.Bind(new IPEndPoint(IPAddress.Parse("192.168.107.14"), 3030));
Task.Run(() =>
{
while (true)
{
byte[] buffer = new byte[1024];
EndPoint ip = new IPEndPoint(IPAddress.None, 0);// 初始化远程终端,没ip ,没端口
soc.ReceiveFrom(buffer, 0, ref ip); //接收了消息,获取远程终端
IPEndPoint ip1 = ip as IPEndPoint; //EndPoint的ip类型 转成IPEndPoint类型
BeginInvoke( new Action(() =>
{
richTextBox1.AppendText($"接收到了来自{ip1.ToString()}的消息:{Encoding.UTF8.GetString(buffer)}\r\n");
}));
}
});
}
//关闭
private void button2_Click(object sender, EventArgs e)
{
soc.Close();
}
//发送
private void button3_Click(object sender, EventArgs e)
{
soc.SendTo(Encoding.UTF8.GetBytes("9福星还有一个大铲子输了"), new IPEndPoint(IPAddress.Parse("192.168.107.46"), 3000));
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
UdpClient
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2UDPClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
UdpClient udp;
private void button1_Click(object sender, EventArgs e)
{
udp = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.107.14"), 3000));
Task.Run(() =>
{
try
{
while (true)
{
IPEndPoint ip = null;
byte[] bs = udp.Receive(ref ip);//接收数据 传递远程终端
string s = Encoding.UTF8.GetString(bs);
BeginInvoke(new Action(() =>
{
richTextBox1.AppendText(ip.ToString() + ":" + s + "\r\n");
}));
}
}
catch (Exception ex)
{
MessageBox.Show("UDP已经关闭");
}
});
}
private void button2_Click(object sender, EventArgs e)
{
udp.Close();
}
private void button3_Click(object sender, EventArgs e)
{
byte[] bs = Encoding.UTF8.GetBytes("今天又周五了,明天可以休息了");
udp.Send(bs,bs.Length,"192.168.107.210",8000);
}
}
}