日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Unity 网络编程(Socket)应用

發(fā)布時(shí)間:2023/12/18 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Unity 网络编程(Socket)应用 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

服務(wù)器端的整體思路:

1、初始化IP地址和端口號(hào)以及套接字等字段;

2、綁定IP啟動(dòng)服務(wù)器,開始監(jiān)聽消息? socketServer.Listen(10);

3、開啟一個(gè)后臺(tái)線程接受客戶端的連接 socketServer.Accept(),這里需要注意的是服務(wù)器端有兩個(gè)Socket,一個(gè)負(fù)責(zé)監(jiān)聽,另一個(gè)負(fù)責(zé)傳輸消息,分工明確;

4、接受客戶端消息? socketMsg.Receive();

5、向客戶端發(fā)送消息 Send(bySendArray);

6、當(dāng)然還應(yīng)該包括信息顯示方法和系統(tǒng)的退出方法。

?

/**** * * 服務(wù)器端 * */using System.Collections; using System.Collections.Generic; using UnityEngine;using System.Text; using System.Threading; using System.Net; using System.Net.Sockets; using UnityEngine.UI; using System;public class Server : MonoBehaviour {public InputField InpIPAdress; //IP地址public InputField InpPort; //端口號(hào)public InputField InpDisplayInfo; //顯示信息public InputField InpSendMsg; //發(fā)送信息public Dropdown Dro_IPList; //客戶端的IP列表private Socket socketServer; //服務(wù)端套接字private bool IsListionContect = true; //是否監(jiān)聽private StringBuilder _strDisplayInfo = new StringBuilder();//追加信息private string _CurClientIPValue = string.Empty; //當(dāng)前選擇的IP地址//保存客戶端通訊的套接字private Dictionary<string, Socket> _DicSocket = new Dictionary<string, Socket>();//保存DropDown的數(shù)據(jù),目的為了刪除節(jié)點(diǎn)信息private Dictionary<string, Dropdown.OptionData> _DicDropdowm = new Dictionary<string, Dropdown.OptionData>();// Start is called before the first frame updatevoid Start(){//控件初始化InpIPAdress.text = "127.0.0.1";InpPort.text = "1000";InpSendMsg.text = string.Empty;//下拉列表處理Dro_IPList.options.Clear(); //清空列表信息//添加一個(gè)空節(jié)點(diǎn)Dropdown.OptionData op = new Dropdown.OptionData();op.text = "";Dro_IPList.options.Add(op);}/// <summary>/// 退出系統(tǒng)/// </summary>public void ExitSystem(){//退出會(huì)話Socket//退出監(jiān)聽Socketif (socketServer != null){try{socketServer.Shutdown(SocketShutdown.Both); //關(guān)閉連接 }catch (Exception){throw;}socketServer.Close(); //清理資源 }Application.Quit();}/// <summary>/// 獲取當(dāng)前好友/// </summary>public void GetCurrentIPInformation(){//選擇玩家當(dāng)前列表_CurClientIPValue = Dro_IPList.options[Dro_IPList.value].text;}/// <summary>/// 服務(wù)端開始監(jiān)聽/// </summary>public void EnableServerReady(){ //需要綁定地址和端口號(hào)IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(InpIPAdress.text), Convert.ToInt32(InpPort.text));//定義監(jiān)聽SocketsocketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//綁定 socketServer.Bind(endPoint);//開始socket監(jiān)聽socketServer.Listen(10);//顯示內(nèi)容DisplayInfo("服務(wù)器端啟動(dòng)");//開啟后臺(tái)監(jiān)聽(監(jiān)聽客戶端連接)Thread thClientCon = new Thread(ListionCilentCon);thClientCon.IsBackground = true; //后臺(tái)線程thClientCon.Name = "thListionClientCon";thClientCon.Start();}/// <summary>/// 接聽到客戶端的連接/// </summary>private void ListionCilentCon(){Socket socMesgServer = null; //會(huì)話Sockettry{while (IsListionContect){//等待接受客戶端連接,此處會(huì)“阻斷”當(dāng)前線程socMesgServer = socketServer.Accept();//獲取遠(yuǎn)程節(jié)點(diǎn)信息string strClientIPAndPort = socketServer.RemoteEndPoint.ToString();//把遠(yuǎn)程節(jié)點(diǎn)信息添加到DropDown控件中Dropdown.OptionData op = new Dropdown.OptionData();op.text = strClientIPAndPort;Dro_IPList.options.Add(op);//把會(huì)話Socket添加到集合中(為后面發(fā)送信息使用) _DicSocket.Add(strClientIPAndPort, socMesgServer);//控件顯示,有客戶端連接DisplayInfo("有客戶端連接");//開啟后臺(tái)線程,接受客戶端信息Thread thClientMsg = new Thread(ReceivMsg);thClientMsg.IsBackground = true;thClientMsg.Name = "thListionClientMsg";thClientMsg.Start(socMesgServer);}}catch (Exception){IsListionContect = false;//關(guān)閉會(huì)話Socketif (socketServer != null){socketServer.Shutdown(SocketShutdown.Both);socketServer.Close();}if (socMesgServer != null){socMesgServer.Shutdown(SocketShutdown.Both);socMesgServer.Close();}}}/// <summary>/// 后臺(tái)線程,接受客戶端信息/// </summary>/// <param name="sockMsg"></param>private void ReceivMsg(object sockMsg){Socket socketMsg = sockMsg as Socket;try{while (true){//準(zhǔn)備接受數(shù)據(jù)緩存byte[] msgAarry = new byte[1024 * 0124];//準(zhǔn)備接受客戶端發(fā)來的套接字信息int trueClientMsgLenth = socketMsg.Receive(msgAarry);//byte數(shù)組轉(zhuǎn)換為字符串string strMsg = System.Text.Encoding.UTF8.GetString(msgAarry, 0, trueClientMsgLenth);//顯示接受的客戶端消息內(nèi)容DisplayInfo("客戶端消息:" + strMsg);}}catch (Exception){}finally{DisplayInfo("有客戶端斷開連接了:" + socketMsg.RemoteEndPoint.ToString());//字典類斷開連接的客戶端消息 _DicSocket.Remove(socketMsg.RemoteEndPoint.ToString());//客戶端列表移除if (_DicDropdowm.ContainsKey(socketMsg.RemoteEndPoint.ToString())){Dro_IPList.options.Remove(_DicDropdowm[socketMsg.RemoteEndPoint.ToString()]);}//關(guān)閉Socket socketMsg.Shutdown(SocketShutdown.Both);socketMsg.Close();}}//向發(fā)送客戶端會(huì)話public void SendMsg(){ //參數(shù)檢查_CurClientIPValue = _CurClientIPValue.Trim();if (string.IsNullOrEmpty(_CurClientIPValue)){DisplayInfo("請(qǐng)選擇要聊天的用戶名稱");return;}//判斷是否與指定的Socket通信if (_DicSocket.ContainsKey(_CurClientIPValue)){//得到發(fā)送的消息string strSendMsg = InpSendMsg.text;strSendMsg = strSendMsg.Trim();if (!string.IsNullOrEmpty(strSendMsg)){//信息轉(zhuǎn)碼byte[] bySendArray = System.Text.Encoding.UTF8.GetBytes(strSendMsg);//發(fā)送數(shù)據(jù) _DicSocket[_CurClientIPValue].Send(bySendArray);//記錄發(fā)送數(shù)據(jù)DisplayInfo("發(fā)送的數(shù)據(jù):" + strSendMsg);//控件重置InpSendMsg.text = string.Empty;}else{DisplayInfo("發(fā)送的消息不能為空!");}}else{DisplayInfo("請(qǐng)選擇合法的聊天用戶!");}}/// <summary>/// 主顯示控件,顯示消息/// </summary>/// <param name="str"></param>private void DisplayInfo(string str){str = str.Trim();if (!string.IsNullOrEmpty(str)){_strDisplayInfo.Append(System.DateTime.Now.ToString());_strDisplayInfo.Append(" ");_strDisplayInfo.Append(str);_strDisplayInfo.Append("\r\n");InpDisplayInfo.text = _strDisplayInfo.ToString();}}// Update is called once per framevoid Update(){} }

客戶端整體思路:

1、初始化IP地址和端口號(hào)以及一些顯示信息和套接字;

2、啟動(dòng)客戶端連接 _SockClient.Connect(endPoint);

3、開啟后臺(tái)線程監(jiān)聽客戶端發(fā)來的信息 _SockClient.Receive(byMsgArray);

4、客戶端發(fā)送數(shù)據(jù)到服務(wù)器??_SockClient.Send(byteArray);

5、當(dāng)然也應(yīng)該包括退出系統(tǒng)和顯示信息方法。

?

/**** * * * 客戶端 * * */ using System.Collections; using System.Collections.Generic; using UnityEngine;using System; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; using UnityEngine.UI;public class Client : MonoBehaviour {public InputField InpIPAdress; //IP地址public InputField InpPort; //端口號(hào)public InputField InpDisplayInfo; //顯示信息public InputField InpSendMsg; //發(fā)送信息private Socket _SockClient; //客戶端Socketprivate IPEndPoint endPoint;private bool _IsSendDataConnection=true; //發(fā)送數(shù)據(jù)連接private StringBuilder _SbDisplayInfo = new StringBuilder();//控件追加信息// Start is called before the first frame updatevoid Start(){InpIPAdress.text = "127.0.0.1";InpPort.text = "1000";}//客戶端退出系統(tǒng)public void ExitSystem(){ //關(guān)閉客戶端Socketif (_SockClient != null){try{//關(guān)閉連接 _SockClient.Shutdown(SocketShutdown.Both);}catch{}//清理資源 _SockClient.Close();}//退出 Application.Quit();}//啟動(dòng)客戶端連接public void EnableClientCon(){ //通訊IP和端口號(hào)endPoint = new IPEndPoint(IPAddress.Parse(InpIPAdress.text), Convert.ToInt32(InpPort.text));//建立客戶端Socket_SockClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);try{//建立連接 _SockClient.Connect(endPoint);//啟動(dòng)線程,監(jiān)聽服務(wù)端返回的消息Thread thrListenMsgFromServer = new Thread(ListionMsgFromServer);thrListenMsgFromServer.IsBackground = true;thrListenMsgFromServer.Name = "thrListenMsgFromServer";thrListenMsgFromServer.Start();}catch (Exception){throw;}//控件顯示連接服務(wù)端成功DisplayInfo("連接服務(wù)器成功!");}/// <summary>/// 后臺(tái)線程監(jiān)聽服務(wù)端返回的消息/// </summary>public void ListionMsgFromServer(){try{while (true){//開辟消息內(nèi)存區(qū)域byte[] byMsgArray = new byte[1024 * 0124];//客戶端接受服務(wù)器返回的數(shù)據(jù)int intTrueMsgLengh = _SockClient.Receive(byMsgArray);//轉(zhuǎn)化為字符串string strMsg = System.Text.Encoding.UTF8.GetString(byMsgArray, 0, intTrueMsgLengh);//顯示收到的消息DisplayInfo("服務(wù)器返回消息:" + strMsg);}}catch{}finally{DisplayInfo("服務(wù)器斷開連接");_SockClient.Disconnect(true);_SockClient.Close();}}//客戶端發(fā)送數(shù)據(jù)到服務(wù)器public void SendMsg(){string strSendMsg = InpSendMsg.text;if (!string.IsNullOrEmpty(strSendMsg)){//字節(jié)轉(zhuǎn)化byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(strSendMsg);//發(fā)送 _SockClient.Send(byteArray);//顯示發(fā)送內(nèi)容DisplayInfo("我:" + strSendMsg);//控件清空InpSendMsg.text = string.Empty;}else{DisplayInfo("提示:發(fā)送信息不能為空!");}}/// <summary>/// 主顯示控件,顯示消息/// </summary>/// <param name="str"></param>private void DisplayInfo(string str){str = str.Trim();if (!string.IsNullOrEmpty(str)){_SbDisplayInfo.Append(System.DateTime.Now.ToString());_SbDisplayInfo.Append(" ");_SbDisplayInfo.Append(str);_SbDisplayInfo.Append("\r\n");InpDisplayInfo.text = _SbDisplayInfo.ToString();}}// Update is called once per framevoid Update(){} }

?

轉(zhuǎn)載于:https://www.cnblogs.com/Optimism/p/10535988.html

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的Unity 网络编程(Socket)应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。