C# socket通讯类
时间: 2023-09-09 18:12:12 浏览: 99
一封装过的C#Socket通讯类
4星 · 用户满意度95%
以下是一个简单的 C# Socket 通讯类,可以用于客户端和服务器端的通讯:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketClient
{
private Socket clientSocket;
public SocketClient()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Connect(string ip, int port)
{
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
}
public void Send(string message)
{
byte[] data = Encoding.UTF8.GetBytes(message);
clientSocket.Send(data);
}
public string Receive()
{
byte[] data = new byte[1024];
int length = clientSocket.Receive(data);
string message = Encoding.UTF8.GetString(data, 0, length);
return message;
}
public void Close()
{
clientSocket.Close();
}
}
public class SocketServer
{
private Socket serverSocket;
private Socket clientSocket;
public SocketServer()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Bind(string ip, int port)
{
serverSocket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
}
public void Listen(int backlog)
{
serverSocket.Listen(backlog);
clientSocket = serverSocket.Accept();
}
public string Receive()
{
byte[] data = new byte[1024];
int length = clientSocket.Receive(data);
string message = Encoding.UTF8.GetString(data, 0, length);
return message;
}
public void Send(string message)
{
byte[] data = Encoding.UTF8.GetBytes(message);
clientSocket.Send(data);
}
public void Close()
{
clientSocket.Close();
serverSocket.Close();
}
}
```
使用示例:
客户端:
```csharp
SocketClient client = new SocketClient();
client.Connect("127.0.0.1", 8888);
client.Send("Hello, server!");
string message = client.Receive();
Console.WriteLine("Received message: " + message);
client.Close();
```
服务器端:
```csharp
SocketServer server = new SocketServer();
server.Bind("127.0.0.1", 8888);
server.Listen(10);
string message = server.Receive();
Console.WriteLine("Received message: " + message);
server.Send("Hello, client!");
server.Close();
```
阅读全文