using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace UnitySocketServer
{
internal class Program
{
static void Main(string[] args)
{
Byte[] BytesOfReceived = new Byte[512]; // 1. 申请字节大小
Socket server = // 2. 设置Socket属性
new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress HostIpAddress = IPAddress.Parse("127.0.0.1"); // 3. 设置IPAddress协议
server.Bind(new IPEndPoint(HostIpAddress, 5600)); // 4. 绑定IPAddress协议
while (true)
{
int NumOfReceived = 0;
NumOfReceived = server.Receive(BytesOfReceived); // 5. 等待接收数据
if (NumOfReceived > 0) // 6. 有数据则打印
{
Console.WriteLine(Encoding.UTF8.GetString(BytesOfReceived));
}
}
}
}
}
Server端执行步骤:
1. 申请字节大小
2. 设置Socket属性
3. 设置IPAddress协议
4. 绑定IPAddress协议
5. 等待接收数据
6. 有数据则打印
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ConsoleApplicationSocket01
{
// 客户端程序
class Program
{
static void Main(string[] args)
{
Byte[] BytesOfSended = // 1. 准备发送字节数组
Encoding.UTF8.GetBytes("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
Socket client = // 2. 置Socket属性(客户端)
new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress HostIpAddress = IPAddress.Parse("127.0.0.1"); // 3. 设置IPAddress协议
client.Bind(new IPEndPoint(HostIpAddress, 5601)); // 4. 绑定IPAddress协议
while (true)
{
int NumOfReceived = // 5. 发送数据到指定端口
client.SendTo(BytesOfSended, new IPEndPoint(HostIpAddress, 5600));
Console.WriteLine($"{NumOfReceived}"); // 6. 打印已发送的字节数
Thread.Sleep(500);
}
}
}
}
Server端执行步骤:
- 准备发送字节数组
- 置Socket属性(客户端)
- 设置IPAddress协议
- 绑定IPAddress协议
- 发送数据到指定端口
- 打印已发送的字节数