栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

unity 使用socket.io 联网,服务器nodejs

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

unity 使用socket.io 联网,服务器nodejs

unity 使用socket.io 联网,服务器nodejs 一、unity前端

代码如下(示例):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SocketioCtrl : SocketIO.SocketIOComponent
{
    new void Awake()
    {
        string host = "127.0.0.1";//替换成服务器ip地址
        string port = "4567";

        url = string.Format("ws://{0}:{1}/socket.io/?EIO=3&transport=websocket", host, port);

        base.Awake();
    }

    new void Start()
    {
        base.Start();


        this.On("connect", (e) =>
        {
            Debug.Log("Socket connect");
        });

        this.On("disconnect", (e) =>
        {
            Debug.Log("Socket disconnect");
        });
    }

    private void _removeEvents()
    {
        this.Off("connect", null);
        this.Off("disconnect", null); ;
    }

    /// 
    /// 发送验证码到服务器
    /// 
    /// 游戏id
    /// 激活码
    private void Verification(object obj)//string gameid, string security_code)
    {
        JSONObject messages = (JSONObject)obj;

        this.Emit("verification", messages, (e) => {

            Debug.Log("verification end " + e);
            long code = long.Parse(e.list[0].ToString());
            string msg = e.list[1].ToString();

            if (code == 200)
            {
               Debug.Log("verification success");
            }
            else
            {
                Debug.LogError(msg);
            }
        });
    }

    new void OnDestroy()
    {
        base.OnDestroy();

        _removeEvents();
    }
}
二、服务器nodejs脚本

代码如下(示例):

var express = require('express');
var app = express();

var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

io.on('connection', function(socket){
	//console.log("user connected>>");
               
	///验证软件是否可用,仅首次登录使用
	socket.on('verification', function(msg, cb){
		//console.log("...............verification..............    ");
		//console.log(msg);
		
	});

	socket.on('disconnect', function(){
		//console.log("user disconnected");
	})
})

server.listen(4567,function(){
    console.log("------- SERVER IS RUNNING -------");
});
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/901145.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号