c#语言 写出Probuff协议的服务器
时间: 2023-07-29 10:07:42 浏览: 65
下面是一个使用 C# 编写 Protobuf 协议的服务器的示例代码:
1. 定义 Protobuf 文件
首先,需要定义 Protobuf 文件,例如:
```
syntax = "proto3";
package MyProtocol;
message Request {
int32 id = 1;
string content = 2;
}
message Response {
int32 id = 1;
string content = 2;
}
```
2. 生成 C# 代码
将上述 Protobuf 文件保存为 `MyProtocol.proto`,然后使用 Protobuf 工具生成 C# 代码。可以通过以下命令行来生成:
```
protoc -I=. --csharp_out=. MyProtocol.proto
```
将生成的 C# 文件添加到项目中,例如 `MyProtocol.cs`。
3. 编写服务器代码
下面是一个简单的使用 Protobuf 协议的服务器代码示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using MyProtocol; // 引入 Protobuf 生成的类
public class Server {
private Socket socket;
public Server() {
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Start() {
socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
socket.Listen(10);
Console.WriteLine("Server started.");
while (true) {
var clientSocket = socket.Accept();
Console.WriteLine("Client connected: {0}", clientSocket.RemoteEndPoint);
var buffer = new byte[1024];
var receivedByteCount = clientSocket.Receive(buffer);
var request = Request.Parser.ParseFrom(buffer, 0, receivedByteCount);
Console.WriteLine("Received request: {0}", request);
var response = new Response {
Id = request.Id,
Content = "Hello, " + request.Content
};
var responseBytes = response.ToByteArray();
clientSocket.Send(responseBytes);
clientSocket.Close();
Console.WriteLine("Client disconnected: {0}", clientSocket.RemoteEndPoint);
}
}
public void Stop() {
socket.Close();
Console.WriteLine("Server stopped.");
}
static void Main(string[] args) {
var server = new Server();
server.Start();
}
}
```
在代码中,首先创建一个 `Socket` 对象,然后绑定地址和端口,并开始监听。当有客户端连接时,接收客户端发送的数据,并通过 Protobuf 解析为 `Request` 对象。然后根据请求内容,创建 `Response` 对象并发送给客户端。最后关闭客户端连接。
需要注意的是,客户端和服务器端的 Protobuf 文件必须完全一致,否则会解析出错。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)