需求
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
编写网页部分
截图如下:
需要源码以及 socketio for unity 包,可私信我。
|