C#写一个socket客户端和服务器
时间: 2023-10-07 21:08:34 浏览: 166
以下是一个简单的C# Socket客户端和服务器的代码示例:
服务器端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Server
{
static void Main(string[] args)
{
IPAddress ipAddress = IPAddress.Any;
int port = 12345;
TcpListener listener = new TcpListener(ipAddress, port);
listener.Start();
Console.WriteLine("Server started on " + ipAddress.ToString() + ":" + port);
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Client connected: " + client.Client.RemoteEndPoint.ToString());
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received message from client: " + message);
byte[] data = Encoding.ASCII.GetBytes("Hello from server!");
stream.Write(data, 0, data.Length);
client.Close();
}
}
}
```
客户端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Client
{
static void Main(string[] args)
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 12345;
TcpClient client = new TcpClient();
client.Connect(ipAddress, port);
Console.WriteLine("Connected to server on " + ipAddress.ToString() + ":" + port);
NetworkStream stream = client.GetStream();
string message = "Hello from client!";
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent message to server: " + message);
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received message from server: " + response);
client.Close();
}
}
```
在这个例子中,服务器监听指定的IP地址和端口,当客户端连接时会处理客户端发送的消息,并回复一个简单的消息。客户端连接到服务器,发送一个简单的消息并等待服务器的响应。请注意,这个示例仅用于演示目的,实际实现时需要考虑更多的异常处理和安全问题。
阅读全文