dotnet core socket编程
时间: 2023-05-19 17:03:07 浏览: 192
Dotnet Core提供了Socket类库,可以用于实现Socket编程。以下是一个简单的Socket服务器示例代码:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketServer
{
class Program
{
static void Main(string[] args)
{
// 创建一个Socket对象
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定IP地址和端口号
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8080);
listener.Bind(localEndPoint);
// 开始监听
listener.Listen(10);
Console.WriteLine("Server started. Waiting for connections...");
while (true)
{
// 接受客户端连接
Socket clientSocket = listener.Accept();
// 处理客户端请求
byte[] buffer = new byte[1024];
int bytesReceived = clientSocket.Receive(buffer);
string request = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
Console.WriteLine("Received request: " + request);
// 发送响应
string response = "Hello, client!";
byte[] responseBuffer = Encoding.ASCII.GetBytes(response);
clientSocket.Send(responseBuffer);
// 关闭连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
}
}
这个示例代码实现了一个简单的Socket服务器,它监听本地IP地址127.0.0.1的8080端口,接受客户端连接并发送响应。当客户端连接时,服务器会输出接收到的请求,并发送一个简单的响应。
阅读全文