IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> 搭建NodeJs服务器,利用SocketIO实现:web、服务器、Unity的通信 -> 正文阅读

[游戏开发]搭建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

编写网页部分

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

需要源码以及 socketio for unity 包,可私信我。

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2022-04-15 00:35:02  更:2022-04-15 00:38:30 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 17:05:07-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码