unity使用protobuf-net见这里
https://blog.youkuaiyun.com/qq_35107322/article/details/110396018
服务器快速安装
1 yum install protobuf-devel
2 项目的make文件加入
-lprotobuf
3 编写proto文件
4 根据proto文件生成c代码
protoc game.proto --cpp_out=./
5 写代码
测试代码;
协议文件
[root@VM_156_144_centos socket_tcp]# vim game.proto
syntax="proto2";
enum MSG_ID
{
MSG_ID_CS_LOGIN_REQ = 1;
MSG_ID_SC_LOGIN_RSP = 2;
}
message CS_LOGIN_REQ
{
}
message SC_LOGIN_RSP
{
optional int32 ret = 1;
}
message MESSAGE_HEAD
{
optional MSG_ID msg_id = 1;
optional int64 user_id = 2;
}
message MESSAGE_BODY
{
optional CS_LOGIN_REQ cs_login_req = 1;
optional SC_LOGIN_RSP sc_login_rsp = 2;
}
message MESSAGE{
optional MESSAGE_HEAD head = 1;
optional MESSAGE_BODY body = 2;
}
unity中打包发送
public static void send_login_req()
{
Message msg = new Message();
msg.Head = new MessageHead();
msg.Body = new MessageBody();
msg.Head.MsgId = MsgId.MsgIdCsLoginReq;
msg.Head.UserId = 123;
send_msg(msg);
}
public static void send_msg(Message msg)
{
MemoryStream ms = new MemoryStream();
Serializer.Serialize<Message>(ms, msg);
byte[] data = ms.ToArray();
Debug.Log("send_msg: size: " + ms.Length.ToString());
sendBuf(data);
}
public void sendBuf(byte[] buf)
{
Thread thrSend = new Thread(SendMessageByBuf);
thrSend.Start(buf);
}
private void SendMessageByBuf(object obj)
{
byte[] buf = (byte[])obj;
try
{
tcpClient.Client.Send(buf);
print("发送完毕: " + " size: " + buf.Length.ToString());
}
catch
{
SocketClose();
}
}
服务器解包代码
using message_cb_fn_t = std::function<int(Session* session, MESSAGE_HEAD* head, MESSAGE_BODY* body)> ;
void GameMessageMgr::on_default_recv_msg(const char* buf, ssize_t nread){
MESSAGE msg;
bool succ = msg.ParseFromArray(buf, nread);
if(succ)
{
if(!msg.has_head())return;
int64_t msgid = msg.head().msg_id();
printf("on_default_recv_msg suc, msgid: %lld, userid: %lld\n", msgid, msg.head().user_id());
message_cb_fn_t cb = get_message_cb(msgid);
if(cb && msg.has_head() && msg.has_body()){
cb(nullptr, &msg.head(), &msg.body());
}
}
else{
printf("on_default_recv_msg fail\n");
}
}
run:
on_default_recv_msg suc, msgid: 1, userid: 9190