This article shares the specific code of Unity's multi-person chat tool for your reference. The specific content is as follows
Code 1:Server code
using UnityEngine; using ; using ; using ; public class ChatServer : MonoBehaviour { // Set the connection port const int portNo = 500; string m_ServerIP = ""; // Use this for initialization void Start () { m_ServerIP = ;//Get the IP of the local server print("Server IP:"+m_ServerIP); //Open a new thread to execute TCP listening (); //Support background operation to avoid running after minimization = true; } private void ListenClientConnect () { ("Station is starting!"); // Initialize the server IP IPAddress localAdd = (m_ServerIP); // Create a TCP listener TcpListener listener = new TcpListener (localAdd, portNo); (); ("The server is running..."); //Warm reminder: It is recommended to use a Windows computer to run the server. If it is a Mac system, you must see the print sentence before the server starts, otherwise the server will not start. // Receive client connection requests in loop while (true) { //Write the classes of each client, and as long as you hear that there is an IP connection to the server, instantiate the corresponding client ChatClient user = new ChatClient (()); // Display the IP and port of the connecting client [As long as a new client is connected in, it will print and click on the console who is coming in] print (user._clientIP + "Join Server\n"); } } }
Code 2:Interaction between client and server
using UnityEngine; using ; using ; using System; using ; //The logic that each client should have [enter the server and leave the server, etc.]public class ChatClient : MonoBehaviour { static Hashtable ALLClients = new Hashtable ();// Client list private TcpClient _client;// Client entity public string _clientIP;// Client IP private string _clientNick;// Client nickname private byte[] data;// Message data private bool ReceiveNick = true;//Whether to receive his nickname from the client [Message splitting ID] void Awake () { = true; } //Create an instance by the server public ChatClient (TcpClient client) { //Client entity object this._client = client; this._clientIP = (); // Add the current client instance to the client list //The IP is the first parameter, the second is the corresponding client (this._clientIP, this); data = new byte[this._client.ReceiveBufferSize]; // Get message from the server ().BeginRead (data, 0, .ToInt32 (this._client.ReceiveBufferSize), ReceiveMessage, null); } // Get message from client void ReceiveMessage (IAsyncResult ar) { int bytesRead; try { lock (this._client.GetStream()) { bytesRead = this._client.GetStream ().EndRead (ar); } //No data is read, which means that the client has been dropped if (bytesRead < 1) { (this._clientIP); //broadcast Broadcast (this._clientNick + "Have left the server");//Have left the server return; } else { string messageReceived = Encoding. (data, 0, bytesRead); //This switch is very critical. After reading the sent data, it will receive the nickname of the corresponding client by default. Use the first message sent by this client as the nickname, and he will send messages in the future. if (ReceiveNick) { this._clientNick = messageReceived; Broadcast (this._clientNick + "Has entered the server");//It has entered the server ReceiveNick = false; } else { Broadcast (this._clientNick + ":" + messageReceived); } } lock (this._client.GetStream()) { //Tail recursive processing this._client.GetStream ().BeginRead (data, 0, .ToInt32 (this._client.ReceiveBufferSize), ReceiveMessage, null); } } catch (Exception ex) { (this._clientIP); Broadcast (this._clientNick + "Have left the server");//Have left the server } } // Send a message to a client void sendMessage (string message) { try { NetworkStream ns; lock (this._client.GetStream()) { ns = this._client.GetStream (); } // Encode the information and write it to the stream. Don't forget to flush and buffer it quickly byte[] bytesToSend = Encoding. (message); (bytesToSend, 0, ); (); } catch (Exception ex) { ("Error:" + ex); } } // Broadcast messages to all clients void Broadcast (string message) { (message);//Print message //Send the latest message to all clients connected in the server foreach (DictionaryEntry c in ALLClients) { ((ChatClient)()).sendMessage (message + ); // \r is Enter, English is Carriage return � // \n is a new line, English is New line � // Enter = Enter + Line Break (\r\n) Confirm key //In a Windows environment, C# Language == "\r\n" // B A // D C // Current edit cursor position: A //The mechanical typewriter has two keys: Enter and line breaks: //Winding line means rolling the drum in one grid without changing the horizontal position. //Enter means resetting the horizontal position without rolling the roller. } } }
Code 3:Client interaction with UI
using UnityEngine; using ; using System; using ; using ; // UI interaction of chats on each clientpublic class ClientHandler : MonoBehaviour { const int portNo = 500; private TcpClient _client; private byte[] data; string nickName = ""; string message = ""; string sendMsg = ""; [SerializeField]InputField m_NickInput; [SerializeField]InputField m_SendMsgInput; [SerializeField]Text m_ShowMessageText; [SerializeField] InputField m_IPInput; void Update () { nickName = m_NickInput.text; m_ShowMessageText.text = message; sendMsg = m_SendMsgInput.text; } //Connect the server button public void ConBtnOnClik () { if (m_IPInput.text != "" || m_IPInput.text != null) { //Real current client this._client = new TcpClient(); //The IP and port of the connection server this._client.Connect(m_IPInput.text, portNo); //Get the number of bit tuples in the buffer, that is, the size of the buffer data = new byte[this._client.ReceiveBufferSize];//Avoid going and dying, for example, some comrades wrote 1024 // After clicking the button to connect to the server, send the nickname to the server. SendMyMessage(nickName); //The current client starts to read the data stream this._client.GetStream() .BeginRead(data, 0, .ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null); } else { ("Please enter the correct IP"); } } //Send message button public void SendBtnOnClik () { //Every time the input message is sent to the server and empty the input box SendMyMessage (sendMsg); m_SendMsgInput.text = ""; } /// <summary> /// Send data to the server (send chat information) /// </summary> /// <param name="message"></param> void SendMyMessage (string message) { try { NetworkStream ns = this._client.GetStream (); //Because we only do text information transmission now, UTF encoding is used here to write and identify byte[] data = Encoding. (message); (data, 0, ); ();//Flush the buffer and prepare to accept new data next time } catch (Exception ex) { ("Error:" + ex); } } /// <summary> /// Receive server data (chat information) /// </summary> /// <param name="ar"></param> void ReceiveMessage (IAsyncResult ar) { try { //When the above reading method is executed, this method will be automatically called back int bytesRead = this._client.GetStream ().EndRead (ar);//Reading is complete if (bytesRead < 1) { //No information was read return; } else { //After reading the text information, use UTF encoding and decoding, and splicing it continuously message += Encoding. (data, 0, bytesRead); } //Read the information again _client.GetStream ().BeginRead (data, 0, Convert.ToInt32 (_client.ReceiveBufferSize), ReceiveMessage, null); } catch (Exception ex) { print ("Error:" + ex); } } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.