基于socket实现的TCP Client 异步通讯代码 C#
时间: 2024-09-11 17:02:16 浏览: 56
在 C# 中实现基于 socket 的 TCP Client 异步通信,通常会使用 `System.Net.Sockets` 命名空间下的 `Socket` 类,并利用异步方法如 `BeginConnect`, `EndConnect`, `BeginReceive`, `EndReceive`, `BeginSend`, `EndSend` 等来完成。以下是一个简单的例子,展示了如何实现一个基本的异步 TCP Client。
首先,需要引入必要的命名空间:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
```
然后,创建一个 TCP Client 类,包含连接、接收和发送数据的方法:
```csharp
public class TcpAsyncClient
{
private Socket clientSocket;
private string serverIp;
private int serverPort;
public TcpAsyncClient(string ip, int port)
{
serverIp = ip;
serverPort = port;
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void ConnectAsync()
{
try
{
clientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(serverIp), serverPort), new AsyncCallback(ConnectCallback), clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
Console.WriteLine("Connected to server...");
ReceiveMessage(client);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void ReceiveMessage(Socket client)
{
try
{
byte[] buffer = new byte[1024];
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), buffer);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
byte[] buffer = (byte[])ar.AsyncState;
int bytesRead = clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + receivedData);
// Send data back as echo or handle the received data accordingly
// EchoMessage(client, receivedData);
}
else
{
Console.WriteLine("Connection closed.");
return;
}
// Continue to receive messages
ReceiveMessage(clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void SendMessage(string message)
{
try
{
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
clientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, new AsyncCallback(SendCallback), clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent " + bytesSent + " bytes to server.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void Close()
{
if (clientSocket.Connected)
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
}
```
使用该类的示例:
```csharp
class Program
{
static void Main(string[] args)
{
TcpAsyncClient client = new TcpAsyncClient("127.0.0.1", 12345);
client.ConnectAsync();
// 在接收到数据时,可以调用 SendMessage 发送消息
// client.SendMessage("Hello, Server!");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
client.Close();
}
}
```
这段代码演示了如何异步连接服务器,接收数据以及发送数据。请注意,这个例子使用了同步方法的回调版本来处理异步操作,并且简单地实现了回声(echo)功能,即收到什么消息就发送什么消息。在实际应用中,你可能需要根据业务逻辑来处理接收到的数据和发送的消息。
阅读全文