C# socket通讯示例
时间: 2023-11-01 15:08:54 浏览: 100
以下是一个简单的 C# socket 通讯示例,其中包括了客户端和服务端的代码:
服务端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server
{
class Program
{
static void Main(string[] args)
{
// 创建一个监听的 socket
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定 IP 地址和端口号
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12345);
listener.Bind(localEndPoint);
// 开始监听
listener.Listen(10);
Console.WriteLine("等待客户端连接...");
while (true)
{
// 接受客户端连接
Socket clientSocket = listener.Accept();
Console.WriteLine("客户端已连接");
// 接收客户端发送的数据
byte[] buffer = new byte[1024];
int count = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, count);
Console.WriteLine("接收到客户端的消息:" + message);
// 发送数据给客户端
string responseMessage = "Hello, Client!";
byte[] responseBuffer = Encoding.UTF8.GetBytes(responseMessage);
clientSocket.Send(responseBuffer);
// 关闭连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
}
}
```
客户端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Client
{
class Program
{
static void Main(string[] args)
{
// 创建一个 socket
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 连接服务器
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345);
clientSocket.Connect(remoteEndPoint);
Console.WriteLine("已连接到服务器");
// 发送数据给服务器
string message = "Hello, Server!";
byte[] buffer = Encoding.UTF8.GetBytes(message);
clientSocket.Send(buffer);
// 接收服务器发送的数据
byte[] responseBuffer = new byte[1024];
int count = clientSocket.Receive(responseBuffer);
string responseMessage = Encoding.UTF8.GetString(responseBuffer, 0, count);
Console.WriteLine("接收到服务器的消息:" + responseMessage);
// 关闭连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
}
```
阅读全文