(连接同一个局域网,可以实现。若连接无线网,只有当前主机才能实现)
发送项目 端口:
class Program
{
//发送端
static void Sender()
{
var socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
while (true)
{
Console.Write("请输入你要发送的内容:");
string content = Console.ReadLine();
socket.SendTo(Encoding.UTF8.GetBytes(content) ,new IPEndPoint(IPAddress.Loopback,9618));
Console.WriteLine("发送成功!!!");
}
}
static void Main(string[] args)
{
Sender();
}
}
接收端口 项目:
class Program
{
//接收端
static void Receiver()
{
var socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, 9618));
Console.WriteLine("创建成功!准备工作...");
byte[] buf = new byte[1024];
var ep = (EndPoint)new IPEndPoint(IPAddress.Any, 9618);
while (true)
{
int n = socket.ReceiveFrom(buf, ref ep);
Console.WriteLine($"接收来自{(ep as IPEndPoint).Address}的信息");
Console.WriteLine(Encoding.UTF8.GetString(buf,0,n));
}
}
static void Main(string[] args)
{
Receiver();
}
}
|