Unity基于TCP的socket通信实现“群聊”功能

发表于2019-01-29
评论0 1.1k浏览

想免费获取内部独家PPT资料库?观看行业大牛直播?点击加入腾讯游戏学院游戏程序行业精英群

711501594
一般游戏都有内置聊天系统,socket 也是常见网络通信方式之一,本篇就分享下使用 socket 基于 TCP 实现游戏中“群聊”功能。

先上效果图:

客户端:可以同时开启多个

服务端:

接下来上代码:

服务端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Socket_Server // 服务端
{
    class Program
    {
        static List<Socket> socketlist = new List<Socket>();
        static void Main(string[] args)
        { 
            // 实例化 socket
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress iP = new IPAddress(new byte[] { 192,168,0,114});
            int port = 6000;
            IPEndPoint point = new IPEndPoint(iP, port); // 绑定 ip 和 port
            server.Bind(point);
            server.Listen(10); // 开启监听
            Console.WriteLine("【系统提示:服务器开启成功...】");
            server.BeginAccept(new AsyncCallback(AcceptClient), server);
            Console.ReadKey();
        }
        static void AcceptClient(IAsyncResult iar)
        {
            Socket server = iar.AsyncState as Socket;
            Socket client = server.EndAccept(iar); // 保存异步链接的客户端
            Console.WriteLine("【系统提示:有新的客户端链接进来...】");
            socketlist.Add(client);
            Console.WriteLine("【客户端IP:】"+client.RemoteEndPoint);
            string msg = "系统信息:欢迎来到联盟";
            byte[] data = Encoding.UTF8.GetBytes(msg);
            client.Send(data); // 发送给客户端
            Thread th = new Thread(ReceiveMsg); // 开启客户端线程
            th.Start(client);
            server.BeginAccept(new AsyncCallback(AcceptClient), server);
        }
        // 接受消息
        static void ReceiveMsg(object obj)
        {
            Socket socket = obj as Socket;
            while (true)
            {
                byte[] buffer = new byte[1024];
                int length = 0;
                try
                {
                    length = socket.Receive(buffer);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message);
                    IPEndPoint point = socket.RemoteEndPoint as IPEndPoint;
                    string ipEndpoint = point.Address.ToString();
                    Console.WriteLine(ipEndpoint + ":退出...");
                    socketlist.Remove(socket);
                    SendMsgToAll(ipEndpoint + ":有客户端退出..."); // 调用群发消息
                    break;
                }
                string resMsg = Encoding.UTF8.GetString(buffer, 0, length);
                IPEndPoint IEP = socket.RemoteEndPoint as IPEndPoint;
                string ip = IEP.Address.ToString();
                string time = DateTime.Now.ToString();
                resMsg = "[" + ip + "  " + time + "]" + ": \n" + resMsg;
                Console.WriteLine(resMsg);
                SendMsgToAll(resMsg);
            }
        }
        // 群发消息
        static void SendMsgToAll(string resMsg)
        {
            // 把就收到的消息群发出去
            for (int i = 0; i < socketlist.Count; i++)
            {
                socketlist[i].Send(Encoding.UTF8.GetBytes(resMsg));
            }
        }
    }
}

客户端:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class Chat : MonoBehaviour {
    Button send;
    InputField msgIput;
    Text showMsg;
    string Message;
    Socket client;
    void Start () {
        send = GameObject.Find("Send").GetComponent<Button>();
        msgIput = GameObject.Find("MsgInput").GetComponent<InputField>();
        showMsg = GameObject.Find("ShowMsg").GetComponent<Text>();
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(new IPEndPoint(IPAddress.Parse("192.168.0.114"), 6000));
        send.onClick.AddListener(SendBtnOnClick);
        Thread th = new Thread(new ThreadStart(ReceiveMsg));
        th.Start();
    }
	void Update () {
        showMsg.text = Message;
	}
    void OnDestroy()
    {
        client.Close();
    }
    void SendBtnOnClick()
    {
        client.Send(Encoding.UTF8.GetBytes(msgIput.text));
        msgIput.text = "";
    }
    void ReceiveMsg()
    {
        while (true)
        {
            byte[] buffer = new byte[1024];
            int length = client.Receive(buffer);
            string resMsg = "\n" + Encoding.UTF8.GetString(buffer, 0, length);
            string str = showMsg.text;
            Debug.Log("收到:" + resMsg);
            Message = str + resMsg;
        }
    }
}

原文链接

著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

游戏学院公众号二维码
腾讯游戏学院
微信公众号

提供更专业的游戏知识学习平台