Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Unity to realize the function of Local area Network chat Room

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to use Unity to achieve the function of local area network chat room". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The whole process is divided into two parts: building the server and building the client.

Server:

General idea:

1. Declare Socket connections and bind IP and ports, which use the

Using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Net;namespace ServerApplication {class Program {public static string IP; public static int Port; static List clientList = new List (); static Socket serverSocket; static void Main (string [] args) {/ / bind IP and port BindIPAndPort () / / while (true) {Socket clientSocket = serverSocket.Accept (); Client client = new Client (clientSocket); clientList.Add (client); Console.WriteLine ("one host enters the connection") } / broadcast data / public static void BroadcostMSG (string s) {List NotConnectedList = new List (); foreach (var item in clientList) {if (item.IsConnected) {item.SendMSG (s) } else {NotConnectedList.Add (item);}} foreach (var item in NotConnectedList) {clientList.Remove (item) }} / bind IP and port / public static void BindIPAndPort () {/ / create a serverSocket serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); / / declare IP and port Console.WriteLine ("enter IP address:") IP = Console.ReadLine (); string ipStr = IP; Console.WriteLine ("Please enter port:"); Port = int.Parse (Console.ReadLine ()); int port = Port; IPAddress serverIp = IPAddress.Parse (ipStr); EndPoint serverPoint = new IPEndPoint (serverIp, port) / / bind serverSocket.Bind (serverPoint) to socket and ip; / / the maximum number of listeners is 100 serverSocket.Listen (100);} using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Threading;namespace ServerApplication {class Client {public Socket clientSocket / / declare a thread to receive information Thread t; / / Container byte [] data = new byte [1024]; / / Constructor public Client (Socket s) {clientSocket = s; t = new Thread (ReceiveMSG); t.Start () } / receive data / void ReceiveMSG () {while (true) {if (clientSocket.Poll (10Magna SelectMode.SelectRead)) {break;} data = new byte [1024] Int length = clientSocket.Receive (data); string message = Encoding.UTF8.GetString (data, 0, length); Program.BroadcostMSG (message); Console.WriteLine ("received message:" + message) }} / send data / public void SendMSG (string message) {byte [] data = Encoding.UTF8.GetBytes (message); clientSocket.Send (data) } / / determine whether this Client object is in the connection state public bool IsConnected {get {return clientSocket.Connected;} client:

A.UI interface

The UI interface is implemented using UGUI

Login users can log in by their own name (for display when speaking). When using it, you need to enter the IP address and port number of the server.

The following is the page of the chat room. Enter the message to be sent in the input box, click Send, and send the message.

This is the information from the server.

b. Script about the client

(1) this is ClientManager, which is responsible for connecting and communicating with the server.

Using System.Collections;using System.Collections.Generic;using UnityEngine;using System.Net.Sockets;using System.Net;using System.Text;using UnityEngine.UI;using System.Threading;public class ClientManager: MonoBehaviour {/ / ip:192.168.1.7 public string ipAddressstr; public int port; public Text ipTextToShow; / / Socket private Socket ClientServer; / / text input field public InputField inputTxt; public string inputMSGStr; / / receive Thread t; public Text receiveTextCom; public string message / / Use this for initialization void Start () {ipTextToShow.text = ipAddressstr; / / ConnectedToServer ();} / / Update is called once per frame void Update () {if (message! = null & & message! = ") {receiveTextCom.text = receiveTextCom.text +"\ n "+ message; message =" }} / Connect to the server / public void ConnectedToServer () {ClientServer = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); / / declare IP address and port IPAddress ServerAddress = IPAddress.Parse (ipAddressstr); EndPoint ServerPoint = new IPEndPoint (ServerAddress, port); ipAddressstr = IpInfo.ipStr; port = IpInfo.portStr / / start to connect to ClientServer.Connect (ServerPoint); t = new Thread (ReceiveMSG); t.Start ();} / receive messages / "string" void ReceiveMSG () {while (true) {if (ClientServer.Connected = = false) {break } byte [] data = new byte [1024]; int length = ClientServer.Receive (data); message = Encoding.UTF8.GetString (data, 0, length); / / Debug.Log ("news coming in") } / send string type data / public void SendMSG () {Debug.Log ("button Clicked"); / / message = "I:" + inputTxt.text; inputMSGStr = inputTxt.text; byte [] data = Encoding.UTF8.GetBytes (IpInfo.name+ ":" + inputMSGStr); ClientServer.Send (data) } private void OnDestroy () {ClientServer.Shutdown (SocketShutdown.Both); ClientServer.Close ();} private void OnApplicationQuit () {OnDestroy ();}}

(2) SceneManager, which is used for scene switching. Here, it is only implemented by SetActive () using GameObject, and a separate Scene is not created for management.

Using System.Collections;using System.Collections.Generic;using UnityEngine;public class SceneManager: MonoBehaviour {public GameObject loginPanel; public GameObject communicatingPanel; / / Use this for initialization public void OnSwitch () {loginPanel.SetActive (false); communicatingPanel.SetActive (true);}}

(3) LogInPanel and IPInfo, one is mounted on the login interface, and the other is the data model, which is used to store data.

Using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;public class LogInPanel: MonoBehaviour {public Text nameInputTxt; public Text ipInputTxt; public Text portInputTxt; / / private string name; / / private string ipStr; / / private string portStr; public void OnLogInClick () {IpInfo.name = nameInputTxt.text; IpInfo.ipStr = ipInputTxt.text; IpInfo.portStr = int.Parse (portInputTxt.text) }} public static class IpInfo {public static string name; public static string ipStr; public static int portStr;} "how to use Unity to achieve local area network chat room function" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report