使用Unity制作一个简单的聊天室

使用控制台作为一个服务器,在Unity中开发客户端,制作一个简易的聊天室,无论哪个客户端发送消息,其他的客户端都会实时的显示出来。

服务器代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Socket聊天室_Server
{
    class Program
    {
        static List clientList = new List();

        public static void BroadcastMessage(string message)
        {
            var notConnectedList=new List();
            foreach (var client in clientList)
            {
                if (client.Connect)
                    client.SendMessageToClient(message);
                else
                {
                    notConnectedList.Add(client);
                }
            }
            foreach (var item in notConnectedList)
            {
                clientList.Remove(item);
            }
        }
        static void Main(string[] args)
        {
            Socket tcpSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip=IPAddress.Parse("192.168.1.21");
            EndPoint point =new IPEndPoint(ip, 6666);
            tcpSever.Bind(point);

            tcpSever.Listen(10);
            Console.WriteLine("Server Is Runing......");

            while (true)
            {
                Socket clientSocket = tcpSever.Accept();
                Console.WriteLine("A Client Is Connected!!!!");
                //把与每个客户端通信的逻辑放到Client类里面进行处理
                Client client = new Client(clientSocket);
                clientList.Add(client);
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace Socket聊天室_Server
{
    /// 
    /// 用来和客户端做通信
    /// 
    class Client
    {
        private Socket clintSocket;
        private Thread thread;
        private byte[] data = new byte[1024];

        public Client(Socket s)
        {
            clintSocket = s;
            //启动一个线程 处理客户端的数据接收
            thread = new Thread(ReceiveMessage);
            thread.Start();
        }

        private void ReceiveMessage() 
        {
            //一直接收客户端的数据
            while (true)
            {
                //在接收数据之前 判断Socket是否断开
                if (clintSocket.Poll(10,SelectMode.SelectRead))
                {
                    clintSocket.Close();
                    break;//跳出循环
                }
                int length = clintSocket.Receive(data);
                string message = Encoding.UTF8.GetString(data,0,length);
                //把接收到的消息分发到各个客户端
                //广播这条消息
                Program.BroadcastMessage(message);
                Console.WriteLine("A Message From Client"+message);
            }
        }

        public void SendMessageToClient(String message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            clintSocket.Send(data);
        }

        public bool Connect
        {
            get
            {
                return clintSocket.Connected;
            }
        }
    }
}

客户端代码

using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using UnityEngine;
using System.Text;
using System.Threading;
using UnityEngine.UI;

/// 
/// Socket聊天室_Client
/// 
public class ChartManager1 : MonoBehaviour {
    public string ip = "192.168.1.21";
    public int port = 6666;
    public InputField textInput;
    public Text chartLabel;

    private Socket clientSocket;
    private Thread thread;
    private byte[] data = new byte[1024];
    private string message = "";

    // Use this for initialization
    void Start() {

        ConnectToSever();
        textInput.text = string.Empty;
    }

    // Update is called once per frame
    void Update() {

        if (message != null && message != "")
        {
            chartLabel.text += "\n" + message;
            message = "";
        }
    }

    //连接服务器
    void ConnectToSever()
    {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));

        //创建一个新的线程用来接收消息
        thread = new Thread(ReceiveMessageFromSever);
        thread.Start();
    }

    //从服务器循环接收消息
    void ReceiveMessageFromSever()
    {
        while (true)
        {
            if (clientSocket.Connected == false)
            {
                break;
            }
            int length = clientSocket.Receive(data);
            message = Encoding.UTF8.GetString(data,0,length);
            //chartLabel.text += "\n" + message;
        }
    }

    void SendMessageToSever(string message)
    {
        byte[] data = Encoding.UTF8.GetBytes(message);
        clientSocket.Send(data);
    }

    public void OnSendButtonClick()
    {
        string value = textInput.text;
        SendMessageToSever(value);
        textInput.text = string.Empty;
    }

    private void OnDestroy()
    {
        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();//关闭连接
    }
}
使用UGUI搭建一个简单的聊天界面

使用Unity制作一个简单的聊天室_第1张图片

先启动服务器,然后运行Unity客户端,尝试输入一些东西

使用Unity制作一个简单的聊天室_第2张图片

将Unity客户端Bulid出来,同时启动多个客户端

使用Unity制作一个简单的聊天室_第3张图片

无论是在哪个客户端输入文字,其他的客户端都会实时的显示出来T_T。



你可能感兴趣的:(Socket)