写一个基于C#的HPSocket通讯
时间: 2024-10-20 07:05:56 浏览: 25
基于HPSocket实现 socket 通讯 - 修正版 ( C# demo 、 C++ dll )
在C#中,创建一个简单的HPSocket通讯(High Performance Socket通信)通常涉及到使用System.Net.Sockets命名空间下的Socket类。以下是一个基本的步骤和代码片段来展示如何创建一个客户端和服务端的例子:
**服务端(Server.cs):**
```csharp
using System;
using System.Net;
using System.Net.Sockets;
public class Server
{
private static TcpListener server;
public static void Main()
{
// 创建TCP服务器监听
server = new TcpListener(IPAddress.Any, 12345);
server.Start();
Console.WriteLine("Server started on port 12345");
while (true)
{
// 等待连接
var client = server.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(HandleConnection, client);
}
}
private static void HandleConnection(object state)
{
using (var client = (TcpClient)state)
{
using (var stream = client.GetStream())
{
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string receivedMessage = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {receivedMessage}");
// 发送回消息
string sendMessage = "Hello from server";
stream.Write(Encoding.ASCII.GetBytes(sendMessage), 0, sendMessage.Length);
}
}
}
}
```
**客户端(Client.cs):**
```csharp
using System;
using System.Net;
using System.Net.Sockets;
public class Client
{
private static TcpClient client;
public static void Main()
{
try
{
// 连接到服务器
client = new TcpClient("localhost", 12345);
Console.WriteLine("Connected to server");
// 获取网络流并发送数据
using (var stream = client.GetStream())
{
string message = "Hello from client";
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent message");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
```
阅读全文