public class ChatMsgC2S
{
public string player;
public string msg;
public int type;
}
public class ChatMsgS2C
{
public string player;
public string msg;
public int type;
}
在MsgHelper.cs中实现聊天业务的处理以及发送聊天消息
/// <summary>
/// 发送聊天消息给服务器
/// </summary>
/// <param name="player"></param>
/// <param name="chat"></param>
public static void SendChatMsg(string player ,string chat)
{
//实例化对象
Module.ChatMsgC2S msg = new Module.ChatMsgC2S();
msg.player = player;
msg.msg = chat;
msg.type = 0;
//将对象序列化
var str = JsonHelper.ToJson(msg);
Debug.Log(str);
//发送消息
SendToService(1003, str);
}
/// <summary>
/// 处理聊天(转发)业务
/// </summary>
/// <param name="data"></param>
public static void ChatMsgHandler(byte[] data)
{
var str = Encoding.UTF8.GetString(data);
var result = JsonHelper.ToObject<Module.ChatMsgS2C>(str);
Client.Instance.msgManager.chatHandle?.Invoke(result);
}
public class ChatMsgC2S
{
public string player;
public string msg;
public int type;
}
public class ChatMsgS2C
{
public string player;
public string msg;
public int type;//0表示其他人的消息,1表示自己的消息
}
在MsgHelper.cs中实现聊天业务的处理以及发送聊天消息
public static void SendChatMsg(Client client, Module.ChatMsgS2C msg)
{
string json = JsonHelper.ToJson(msg);
client.SendToService(1003, json);
}
/// <summary>
/// 处理聊天业务
/// </summary>
/// <param name="data"></param>
public static void ChatMsgHandler(byte[] data, Client client)
{
var msg = JsonHelper.ToObject<Module.ChatMsgC2S>(data);
Module.ChatMsgS2C response = new Module.ChatMsgS2C();
response.player = msg.player;
response.msg = msg.msg;
response.type = 0;
//获取所有在线玩家
var users = PlayerData.Instance.GetAllLoginUser();
//向其他所有在线玩家发送消息
foreach(var user in users)
{
if (user.Value == client)
continue;
SendChatMsg(user.Value, response);
}
//向自己发送消息
response.type = 1;
SendChatMsg(client, response);
}