代码如下(示例):
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 -------");
});



