Dotnet core socket通信代码
时间: 2023-05-19 16:03:29 浏览: 177
可以参考以下代码:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketServer
{
class Program
{
static void Main(string[] args)
{
StartServer();
}
static void StartServer()
{
byte[] buffer = new byte[1024];
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 1234);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEP);
listener.Listen(10);
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
while (true)
{
int bytesRec = handler.Receive(buffer);
string data = Encoding.ASCII.GetString(buffer, 0, bytesRec);
Console.WriteLine($"Received: {data}");
if (data.IndexOf("<EOF>") > -1)
{
break;
}
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
这是一个简单的 Socket 服务器代码,它监听本地 1234 端口,接收客户端发送的数据并将其原样返回。
阅读全文