c# 手写socket套接字
时间: 2024-12-06 20:10:33 浏览: 5
在C#中,你可以手动编写TCP或UDP套接字(Socket)来实现网络通信。以下是一个简单的例子,展示如何创建一个TCP服务器端和客户端:
**TCP服务器端(Server.cs)**:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
class Server
{
static void Main()
{
TcpListener listener = new TcpListener(IPAddress.Any, 1234); // 设置IP地址和端口
listener.Start();
Console.WriteLine("Server started. Listening on port {0}", listener.LocalEndpoint.Port);
while (true)
{
TcpClient client = listener.AcceptTcpClient();
HandleClient(client);
}
}
static void HandleClient(TcpClient client)
{
NetworkStream stream = client.GetStream();
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
string message = reader.ReadLine();
Console.WriteLine($"Received from client: {message}");
writer.WriteLine("Hello, Client!");
}
client.Close();
}
}
```
**TCP客户端(Client.cs)**:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
class Client
{
static void Main()
{
TcpClient client = new TcpClient("localhost", 1234); // 连接到服务器的IP地址和端口
NetworkStream stream = client.GetStream();
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine("Hello, Server!"); // 发送消息
}
using (StreamReader reader = new StreamReader(stream))
{
string response = reader.ReadLine();
Console.WriteLine($"Response from server: {response}");
}
client.Close();
}
}
```
在这个示例中,服务器等待连接请求,接受新连接并处理来自客户端的消息。客户端则建立连接并向服务器发送信息,接收响应并关闭连接。
阅读全文