聊天室C#服务器Unity客户端UGUI显示

服务器端脚本代码:

using System;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 聊天室
{
    class Client
    {
        public Socket clientSocket;
        private Thread mesManageThread;

        public Client(Socket soc)
        {
            clientSocket = soc;
            mesManageThread = new Thread(MessageSendFromClient);
            mesManageThread.Start();
        }

        public void MessageSendFromClient()
        {
            while(true)
            {
                byte[] buffer = new byte[2048];                 //临时开辟byte2048长度
                if(clientSocket.Poll(10,SelectMode.SelectRead)==true)
                {
                    clientSocket.Close();
                    break;                                     //终止协程
                }
                int bytNum = clientSocket.Receive(buffer);     //从客服端接收信息
                string mes = Encoding.UTF8.GetString(buffer, 0, bytNum);        //utf8编码
                Console.WriteLine("客户端消息:" + mes);
                Program.CastMessageToALLConneredClients(mes);   //castmessage,广播消息给每个客户端
            }
        }

        /// 
        ///send message to client 
        /// 
        /// 
        public void CastMessage(string message)
        {
            byte[] date = Encoding.UTF8.GetBytes(message);
            clientSocket.Send(date);
        }

        /// 
        /// is or not conneted;
        /// 
        public bool Conneted
        {
            get
            {
                return clientSocket.Connected;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace 聊天室
{
    class Program
    {
        static List clients = new List();
        static List notClients = new List();

        /// 
        /// 广播
        /// 
        /// 
        public static void CastMessageToALLConneredClients(string message)
        {
            foreach (var client in clients)
            {
                if (client.Conneted)
                {
                    client.CastMessage(message);
                }
                else
                {
                    notClients.Add(client);
                }
            }
            foreach (var item in notClients)
            {
                clients.Remove(item);
            }
        }

        static void Main(string[] args)
        {
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            tcpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.109"), 8899));
            tcpServer.Listen(100);                                            //监听客户端发起连接
            Console.WriteLine("begin to listen...");

            while(true)
            {
                Socket clientSocet = tcpServer.Accept();
                if (clientSocet != null)
                {
                    Console.WriteLine("A client has conneted...");
                    Client client = new Client(clientSocet);    //将每个新创建的连接通信放于client类做通信
                    clients.Add(client);
                }
            }
        }
    }
}

unity客户端代码:ugui:两个输入框:网名框+聊天内容框。一个发送的button按钮,一个展示聊天内容的Text文本框。有public状态可以直接拖入。

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

public class ChatManager : MonoBehaviour {

    private string ipStr = "192.168.0.109";
    private int port = 8899;
    EndPoint remotPoint;
    Socket clientSocket;
    public InputField inputName;
    public InputField inputMessage;                         //输入框
    public Text text;                                     //聊天记录显示
    //private bool isCanSend = false;
    private string buttonMessage = string.Empty;                  //输入框内容

    Thread receiveThread;
    byte[] bufferReceive = new byte[2048];

    private string message = string.Empty;                        //聊天内容()

	void Start () {
        ConnetToServer(ipStr, port);
	}
	
	// Update is called once per frame
	void Update () {
		if(message!=""&&message!=null)
        {
            text.text += "\n" +System.DateTime.Now.ToString("T")+" :  "+ message;
            message = "";
        }
	}

    private new void SendMessage(string message)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(message);
        clientSocket.SendTo(buffer, remotPoint);
    }

    public void OnSendButtonClick()
    {
        if(inputMessage.text!=null)
        {
            buttonMessage = inputName.text+":“"+inputMessage.text+"”";
        }
        else
        {
            buttonMessage = string.Empty;
        }
        SendMessage(buttonMessage);
        inputMessage.text = null;                                 //
    }

    private void ConnetToServer(string ipAdress,int port)
    {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        remotPoint = new IPEndPoint(IPAddress.Parse(ipAdress), port);
        clientSocket.Connect(remotPoint);
        receiveThread = new Thread(ReceiveMessageFormSever);
        receiveThread.Start();
        
    }
    private void ReceiveMessageFormSever()
    {
        while(true)
        {
            if(clientSocket.Connected)
            {
                int lenth = clientSocket.Receive(bufferReceive);
                message = Encoding.UTF8.GetString(bufferReceive, 0, lenth);
            }
            else
            {
                break;
            }
        }
    }
}

效果:
聊天室C#服务器Unity客户端UGUI显示_第1张图片

你可能感兴趣的:(Unity,UI,vs2017)