Unity-网络编程 笔记5

聊天功能实现

客户端实现

创建消息的json对象

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);
}

在ChatView.cs中聊天消息的发送以及消息的回调 

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChatView : MonoBehaviour
{
    [SerializeField] private Button closeBtn;

    [SerializeField] private GameObject chatItem0;
    [SerializeField] private GameObject chatItem1;
    [SerializeField] private Transform chatItemParent;
    [SerializeField] private Scrollbar scrollbar;
    [SerializeField] private Button sendBtn;
    [SerializeField] private InputField sendInput;
    
    
    void Start()
    {
        closeBtn = transform.Find("Popup_Dark/Menu Icon").GetComponent<Button>();
        sendBtn = this.transform.Find("SendBtn").GetComponent<Button>();

        chatItem0 = Resources.Load<GameObject>("ChatItem0");
        chatItem1 = Resources.Load<GameObject>("ChatItem1");
        chatItemParent = this.transform.Find("ScrollView/Viewport/Content");
        scrollbar = this.transform.Find("ScrollView/Vertical").GetComponent<Scrollbar>();
        sendInput = this.transform.Find("SendInput").GetComponent<InputField>();


        closeBtn.onClick.AddListener(LogoutHandle);
        sendBtn.onClick.AddListener(Send);

        Client.Instance.msgManager.chatHandle += ChatHandle;
    }

    private void ChatHandle(Module.ChatMsgS2C c)
    {
        AddMessage(c.player,c.msg,c.type);
    }

    private void AddMessage(string title,string content,int type)
    {
        GameObject item = null;
        if(type == 0)
            item = Instantiate(chatItem0, chatItemParent);
        else
            item = Instantiate(chatItem1, chatItemParent);

        ChatItem component = item.AddComponent<ChatItem>();
        component.Init(title, content);

        scrollbar.value = 0;
    }

    private void Send()
    {
        //判断输入
        if (string.IsNullOrEmpty(sendInput.text))
            return;
        //向服务端发送消息
        MsgHelper.SendChatMsg(PlayerData.Instance.LoginMsgS2C.username, sendInput.text);
        //将输入框滞空
        sendInput.text = string.Empty;
    }

    private void LogoutHandle()
    {
        if(PlayerData.Instance.LoginMsgS2C != null)
        {
            MsgHelper.SendLogoutMsg(PlayerData.Instance.LoginMsgS2C.username, PlayerData.Instance.LoginMsgS2C.password);
            PlayerData.Instance.LoginMsgS2C = null;
        }
    }
}

服务端实现

创建json对象

 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);
}

 最终效果

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shumake

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值