阅读背景:

Unity聊天室Tcp协议

来源:互联网 

客户端unity脚本

using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using UnityEngine; using UnityEngine.UI; public class UIManager : MonoBehaviour { private string ipaddress = "192.168.3.35"; private int port = 7788; private Thread t; //创建一个线程方便管理 private byte[] data = new byte[1024]; private string message = "";//Text用来接收Message的容器 public Text text; //聊天框 public InputField textInput; //输入框 private Socket clientSocket; // Use this for initialization void Start () { ConnectedToServer(); } // Update is called once per frame void Update () { if (message!=null&&message!="") { text.text += "\n" + message; message = "";//清空消息 } } //和服务器连接的方法 private void ConnectedToServer() { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //发起连接 clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress), port)); //创建一个线程用来接收消息 t = new Thread(ReceiveMeage); t.Start(); } /// <summary> /// 用来循环接收消息 /// </summary> void ReceiveMeage() { while (true) { //判断是否和服务器连接 if (clientSocket.Connected==false) { break; } int length = clientSocket.Receive(data); message = Encoding.UTF8.GetString(data, 0, length); //text.text += "\n" + message; //unity不允许单独的线程操纵unity组件 } } //UI界面发送按钮的方法 public void SendMessage(string message) { //字符串转成字节数组 byte[] data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); //发送到服务器端 } //当按钮点击的时候获取文本框内的信息 public void OnSendButtonClick() { string value = textInput.text; //得到文本框内的内容 SendMessage(value); //发送完输入框为空 textInput.text = ""; } //防止客户端断开连接服务器一直接收消息 private void OnDestroy() { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close();//关闭连接 } } using System.Collections; using System.



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: