当前位置:   article > 正文

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

unity socket.io

需求

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;
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

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

编写 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);
    });
	
});


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68

启动服务器

node server.js
  • 1

编写网页部分

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

资源链接:

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

免费获取源码

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/771989
推荐阅读
相关标签
  

闽ICP备14008679号