Unity3d简单的socket通信
生活随笔
收集整理的這篇文章主要介紹了
Unity3d简单的socket通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
vs2010或其他創建C#工程
C#端代碼一:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets;namespace SoketDemo {class Program{// 設置連接端口const int portNo = 500;static void Main(string[] args){// 初始化服務器IPSystem.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1");// 創建TCP偵聽器TcpListener listener = new TcpListener(localAdd, portNo);listener.Start();// 顯示服務器啟動信息Console.WriteLine("Server is starting...\n");// 循環接受客戶端的連接請求while (true){ChatClient user = new ChatClient(listener.AcceptTcpClient());// 顯示連接客戶端的IP與端口Console.WriteLine(user._clientIP + " is joined...\n");}}}代碼二:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Net.Sockets;namespace SoketDemo {class ChatClient{public static Hashtable ALLClients = new Hashtable(); // 客戶列表private TcpClient _client; // 客戶端實體public string _clientIP; // 客戶端IPprivate string _clientNick; // 客戶端昵稱private byte[] data; // 消息數據private bool ReceiveNick = true;public ChatClient(TcpClient client){this._client = client;this._clientIP = client.Client.RemoteEndPoint.ToString();// 把當前客戶端實例添加到客戶列表當中ALLClients.Add(this._clientIP, this);data = new byte[this._client.ReceiveBufferSize];// 從服務端獲取消息client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);}// 從客戶端獲取消息public void ReceiveMessage(IAsyncResult ar){int bytesRead;try{lock (this._client.GetStream()){bytesRead = this._client.GetStream().EndRead(ar);}if (bytesRead < 1){ALLClients.Remove(this._clientIP);Broadcast(this._clientNick + " has left the chat");return;}else{string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);if (ReceiveNick){this._clientNick = messageReceived;Broadcast(this._clientNick + " has joined the chat.");//this.sendMessage("hello");ReceiveNick = false;}else{Broadcast(this._clientNick + ">" + messageReceived);}}lock (this._client.GetStream()){this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);}}catch (Exception ex){ALLClients.Remove(this._clientIP);Broadcast(this._clientNick + " has left the chat.");}}// 向客戶端發送消息public void sendMessage(string message){try{System.Net.Sockets.NetworkStream ns;lock (this._client.GetStream()){ns = this._client.GetStream();}// 對信息進行編碼byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);ns.Write(bytesToSend, 0, bytesToSend.Length);ns.Flush();}catch (Exception ex){}}// 向客戶端廣播消息public void Broadcast(string message){Console.WriteLine(message);foreach (DictionaryEntry c in ALLClients){((ChatClient)(c.Value)).sendMessage(message + Environment.NewLine);}}} }?unity端代碼,直接掛載到攝像頭:
using UnityEngine; using System.Collections;using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Net.Sockets;public class ClientHandler : MonoBehaviour {const int portNo = 500;private TcpClient _client;byte[] data;public string nickName = "";public string message = "";public string sendMsg = "";void OnGUI(){nickName = GUI.TextField(new Rect(10, 10, 100, 20), nickName);message = GUI.TextArea(new Rect(10, 40, 300, 200), message);sendMsg = GUI.TextField(new Rect(10, 250, 210, 20), sendMsg);if (GUI.Button(new Rect(120, 10, 80, 20), "Connect")){//Debug.Log("hello");this._client = new TcpClient();this._client.Connect("127.0.0.1", portNo);data = new byte[this._client.ReceiveBufferSize];//SendMessage(txtNick.Text); SendMessage(nickName);this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);};if (GUI.Button(new Rect(230, 250, 80, 20), "Send")){SendMessage(sendMsg);sendMsg = "";};}public void SendMessage(string message){try{NetworkStream ns = this._client.GetStream();byte[] data = System.Text.Encoding.ASCII.GetBytes(message);ns.Write(data, 0, data.Length);ns.Flush();}catch (Exception ex){//MessageBox.Show(ex.ToString()); }}public void ReceiveMessage(IAsyncResult ar){try{int bytesRead;bytesRead = this._client.GetStream().EndRead(ar);if (bytesRead < 1){return;}else{Debug.Log(System.Text.Encoding.ASCII.GetString(data, 0, bytesRead));message += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);}this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);}catch (Exception ex){}} }這樣就得了。
?
轉載于:https://www.cnblogs.com/boye666/p/6531276.html
總結
以上是生活随笔為你收集整理的Unity3d简单的socket通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Intellij] 软件设置和常用快捷
- 下一篇: D3学习之地图