搭建NodeJs服务器,利用SocketIO实现:web、服务器、Unity的通信

需求

1、unity 链接 socketio 服务器
2、网页实时发送信息到 Unity
3、实时统计设备数量

编写Unity socketIO

在 Unity store搜索,socket.io,找到Socket.IO V3 / V4 Client for Unity插件,下载到 Unity。
代码如下:

using System;
using Firesplash.UnityAssets.SocketIO;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class ScoketIOTest : MonoBehaviour
{
    public Text txtSID, txtPing, txtPong, txtLosses, txtDC,messageUI;
    public String roomID;
    SocketIOCommunicator sioCom;
    int pings = 0, pongs = 0, losses = 0, dcs = 0;
    bool pongReceived = false;

    void  Start()
    {
        sioCom = GetComponent<SocketIOCommunicator>();

        sioCom.Instance.On("connect", (payload) =>
        {
            Debug.Log("Connected! Socket ID: " + sioCom.Instance.SocketID);
            txtSID.text = "SocketID: " + sioCom.Instance.SocketID;
            StartCoroutine(joinRoom(roomID));
        });
        sioCom.Instance.On("message", (data) =>
        {
            Debug.Log("message: " + data);
            messageUI.text = "Message: "+data;
        });
        sioCom.Instance.On("disconnect", (payload) =>
        {
            Debug.LogWarning("Disconnected: " + payload);
            txtDC.text = "Disconnects: " + ++dcs;
            txtSID.text = "SocketID: <i>lost connection to server</i>";
        });

        sioCom.Instance.On("PONG", (seqno) =>
        {
            if (int.Parse(seqno) != pings)
            {
                Debug.LogWarning("Received PONG with SeqNo " + seqno + " out of order. Ignoring.");
            }
            else
            {
                pongReceived = true;
                txtPong.text = "PONGs sent: " + ++pongs;
            }
        });

        sioCom.Instance.Connect();
        StartCoroutine(Pinger());
    
    }

    IEnumerator joinRoom(String room)
    {
        yield return new WaitUntil(() => sioCom.Instance.IsConnected());
        sioCom.Instance.Emit("join", roomID);
    }

    IEnumerator Pinger()
    {
        while(true)
        {
            //we will not send if we are not connected
            yield return new WaitUntil(() => sioCom.Instance.IsConnected());

            pongReceived = false;
            sioCom.Instance.Emit("PING", (++pings).ToString(), true);
            txtPing.text = "PINGs sent: " + pings;

            //we will wait 3 seconds after each ping
            yield return new WaitForSeconds(3);

            //Check if the server PONGed back
            if (!pongReceived)
            {
                losses++;
                txtLosses.text = "Losses: " + losses;
            }
        }
    }
}

界面截图如下
在这里插入图片描述

编写 nodejs 服务器

const io = require('socket.io')(8123, { //8123 is the local port we are binding the demo server to
  pingInterval: 30005,		//An interval how often a ping is sent
  pingTimeout: 5000,		//The time a client has to respont to a ping before it is desired dead
  upgradeTimeout: 3000,		//The time a client has to fullfill the upgrade
  allowUpgrades: true,		//Allows upgrading Long-Polling to websockets. This is strongly recommended for connecting for WebGL builds or other browserbased stuff and true is the default.
  cookie: false,			//We do not need a persistence cookie for the demo - If you are using a load balöance, you might need it.
  serveClient: true,		//This is not required for communication with our asset but we enable it for a web based testing tool. You can leave it enabled for example to connect your webbased service to the same server (this hosts a js file).
  allowEIO3: false,			//This is only for testing purpose. We do make sure, that we do not accidentially work with compat mode.
  cors: {
    origin: "*"				//Allow connection from any referrer (most likely this is what you will want for game clients - for WebGL the domain of your sebsite MIGHT also work)
  }
});


//This funciton is needed to let some time pass by between conversation and closing. This is only for demo purpose.
function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}  

// App Code starts here

console.log('Starting Socket.IO demo server');

io.on('connection', (socket) => {
	console.log('[' + (new Date()).toUTCString() + '] game connecting');
	
    socket.on('KnockKnock', (data) => {
		console.log('[' + (new Date()).toUTCString() + '] game knocking... Answering "Who\'s there?"...');
        socket.emit('WhosThere');
    });

    socket.on('ItsMe', async (data) => {
		console.log('[' + (new Date()).toUTCString() + '] received game introduction. Welcoming the guest...');
        socket.emit('Welcome', 'Hi customer using unity' + data.version + ', this is the backend microservice. Thanks for buying our asset. (No data is stored on our server)');
        socket.emit('TechData', {
			podName: 'Local Test-Server',
			timestamp: (new Date()).toUTCString()
		});
    });
	
	socket.on('SendNumbers', async (data) => {
		console.log('[' + (new Date()).toUTCString() + '] Client is asking for random number array');
		socket.emit('RandomNumbers', [ Math.ceil((Math.random() * 100)), Math.ceil((Math.random() * 100)), Math.ceil((Math.random() * 100)) ]);
	});
	
	socket.on('Goodbye', async (data) => {
		console.log('[' + (new Date()).toUTCString() + '] Client said "' + data + '" - The server will disconnect the client in five seconds. You can now abort the process (and restart it afterwards) to see an auto reconnect attempt.');
		await sleep(5000); //This is only for demo purpose.
		socket.disconnect(true);
	});

	socket.on('disconnect', (data) => {
		console.log('[' + (new Date()).toUTCString() + '] Bye, client ' + socket.id);
	});


	
	socket.on('PING', async (data) => {
		console.log('[' + (new Date()).toUTCString() + '] incoming PING #' + data + ' from ' + socket.id + ' answering PONG with some jitter...');
		await sleep(Math.random() * 2000);
        socket.emit('PONG', data);
    });
	
});


启动服务器

node server.js

编写网页部分

截图如下:
在这里插入图片描述

资源链接:

https://download.csdn.net/download/u014196765/86776723

免费获取源码

公众号回复:socketio
公众号链接

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小~小

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值