您当前的位置: 首页 >  服务器

程序员正茂

暂无认证

  • 2浏览

    0关注

    283博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Nodejs(Socket.IO)作为Unity服务器的实时通信

程序员正茂 发布时间:2020-08-20 15:23:54 ,浏览量:2

一、搭建服务端

1.安装Node.js。从官网下载node.js,下载后双击安装文件,选择自动安装工具,其余都点下一步即可。

2.在D:\Tmp下新建文件夹SocketServer1,在SocketServer1中新建文件index.js。index.js内容如下。

const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8080 },()=>{
    console.log('server started')
})
wss.on('connection', function connection(ws) {
   ws.on('message', (data) => {
      console.log('data received \n %o',data)
      ws.send(data);
   })
})
wss.on('listening',()=>{
   console.log('listening on 8080')
})

4.启动cmd,并转到SocketServer1文件夹下,使用如下命令安装socket.io

npm install socket.io

5.启动服务端,Ctrl+C可停止服务端。

node index.js

二、编写客户端 

1.下载NuGetForUnity(https://github.com/GlitchEnzo/NuGetForUnity/releases/tag/v3.0.2)

2.新建unity工程,导入NuGetForUnity.3.0.2.unitypackage到Unity 3.下载WebSocketSharp-netstandard

 

 4.创建一个空实体,挂上一个代码WsClient

using UnityEngine;
using WebSocketSharp;
public class WsClient : MonoBehaviour
{
    WebSocket ws;
    private void Start()
    {
        ws = new WebSocket("ws://localhost:8080");
        ws.Connect();
        ws.OnMessage += (sender, e) =>
        {
            Debug.Log("Message Received from " + ((WebSocket)sender).Url + ", Data : " + e.Data);
        };
    }
    private void Update()
    {
        if (ws == null)
        {
            return;
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ws.Send("Hello");
        }
    }
}

3.运行unity程序,按空格,即可看到服务端收到hello。

 

关注
打赏
1660743125
查看更多评论
立即登录/注册

微信扫码登录

0.0358s