Unity3D与Node.js通过TCP通信.

来源:互联网 发布:组态软件下载 编辑:程序博客网 时间:2024/05/29 02:12

今天研究了一天.终于把这套东西给搞通了.其实很简单.需要的代码也不是很多...就是中间走了不少弯路.

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 孤独拜.!




原创粉丝点击