您当前的位置: 首页 >  unity

莉萝爱萝莉

暂无认证

  • 4浏览

    0关注

    58博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

unity通过socket.io联网

莉萝爱萝莉 发布时间:2021-03-15 23:56:42 ,浏览量:4

unity前端部分
/* 
新建空对象,引入模块Socket IO  Component
Url: 表示连接的地址
自动连接:自动断线重连
Reconnect Delay: 重连间隔
Ping Interval:心跳连接间隔
Ping Timeout:心跳连接超时
*/ 
socketIO.On("connect", (e) => { Debug.Log("连接成功"); });
socketIO.On("connecting", (e) => { Debug.Log("正在连接"); });
socketIO.On("disconnect", (e) => { Debug.Log("断开连接"); });
socketIO.On("connect_failed", (e) => { Debug.Log("连接失败"); });
socketIO.On("error", (e) => { Debug.Log("错误发生,并且无法被其他事件类型所处理"); });
socketIO.On("message", (e) => { Debug.Log("同服务器端message事件"); });
socketIO.On("anything", (e) => { Debug.Log("同服务器端anything事件"); });
socketIO.On("reconnect_failed", (e) => { Debug.Log("重连失败"); });
socketIO.On("reconnect", (e) => { Debug.Log("成功重连"); });
socketIO.On("reconnecting", (e) => { Debug.Log("正在重连"); });
//上传数据
Dictionary data = new Dictionary();
data["username"] = "liluo";
data["password"] = "000";
socketIO.Emit("login", new JSONObject(data));
//接受数据
socketIO.On("login", (e) =>
{
	// 这是接受的json数据
	Debug.Log(e.data);
	// 转换为字符串
	string jsonTest = e.data.ToString();
	// 解析字符串
	ModelTest obj = JsonUtility.FromJson(jsonTest);
	// 得到的字符串
	Debug.Log(obj.statu);
	// 得到的数字
	Debug.Log(obj.number);
	// 得到的数组
	foreach (int inter in obj.list)
	{
		Debug.Log(inter);
	}
});
// 解析出来的结果的类型
[System.Serializable]
public class ModelTest
{
	public string statu;
	public int number;
	public int[] list;
}
// 输入框输入的文本记得去掉最后的\n
string name = inputName.GetComponent().text;
name = name.Substring(0, name.Length - 1);
node.js后端部分
// 监听8001
var io = require('socket.io')(8001);
// 连接成功
io.on('connection', function (socket) { console.log('用户连接');
  socket.on('show', function(msg) {
    // msg:json对象
    // 加入房间
    socket.join('game');
    // 离开房间
    socket.leave('game');
    io.emit("给所有人");
    socket.emit("给链连接者");
    socket.to(msg).emit('hey', 'I just met you');
    socket.broadcast.emit('给除去链接者');
    socket.to('game').emit("给除去连接者该房间的所有人");
    socket.in('game').emit("给该房间的所有人");
  });

    //断开消息
    socket.on('disconnect', function () { console.log('用户登出'); });
});

关注
打赏
1663903574
查看更多评论
立即登录/注册

微信扫码登录

0.0536s