Unity3D與Node.js通過TCP通訊.

來源:互聯網
上載者:User

今天研究了一天.終於把這套東西給搞通了.其實很簡單.需要的代碼也不是很多...就是中間走了不少彎路.

Node.js端.需要的庫就是我LighterWebEngine的TCP封裝. 可以去我的Github上面下載,

var tcp = require("./LighterWebEngine/TCP");tcp.CreateServer(10000,    function(){ //初始化回調    },    function(hSocket, sBuffer){ //有用戶端發送訊息過來.. sBuffer就是資料.         console.log(sBuffer.toString()); //列印用戶端發來的訊息 "join success!"    },    function(hSocket){ //和用戶端中斷連線    },    function(hSocket){ //串連成功        hSocket.write('hello World!'); //發送給用戶端一個 "hello world"        hSocket.end();    });

unity3d這邊其實非常簡單..mono就是c#嘛..c#有個tcpclient庫.直接載入就可以使用了哈.

using System.Net.Sockets; using System.Text;

需要先using該兩個命名空間.

TcpClient tcpClient = new TcpClient(); //建立一個本地串連 連接埠是10000的tcpClient.Connect("127.0.0.1", 10000);NetworkStream clientStream = tcpClient.GetStream(); //擷取stream. 通過stream可以收資料和發資料byte[] message = new byte[4096];int bytesRead;bytesRead = 0;bytesRead = clientStream.Read(message, 0, 4096); //收到資料 "hello world!"UTF8Encoding encoder = new UTF8Encoding();MonoBehaviour.print(encoder.GetString(message, 0, bytesRead)); //轉化資料為utf8字串並列印出來byte[] outStream = Encoding.UTF8.GetBytes("joining success!"); //發送一個加入成功的包給伺服器.clientStream.Write(outStream, 0, outStream.Length);clientStream.Flush();tcpClient.Close(); //關閉串連

有什麼問題可以給我留言. 太晚了睡覺了 see you 孤獨拜.!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.