socket io:如何在客户端和第二台服务器之间建立连接?

yiytaume  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(187)

我需要开发的系统需要客户端连接到具有已知地址和端口的入口服务器。根据es和客户机之间共享的一些数据,条目服务器从列表中选择一个服务器(称为“匹配器”),并将详细信息发送给客户机。然后,客户端必须建立与此“匹配器”(新服务器)的连接。
客户端使用两个套接字示例:
“套接字”:在开始时使用已知地址和端口定义('localhost:3000')
“socket_matcher”:只能在通过“socket_es”上发出的“assign_matcher”事件接收到地址和端口后定义。
es和客户机之间的连接按预期工作。但是,客户端不注册“套接字匹配器”上发出的事件,但匹配器会注册。在客户端中,socket\u matcher.emit()事件起作用,但socket\u matcher.on()不起作用。
我不熟悉js、node.js和socket.io。非常感谢您的帮助。
客户端代码:

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {

    var socket_ES = io.connect("http://localhost:3000");
    var socket_Matcher = io(); // Matcher is not yet assigned

    // ES asking for info, reply with myInfo
    socket_ES.on('join_info', function(msg) {
        socket_ES.emit('client_join', myInfo);
    });

    //ES is giving client the matcher info          
    socket_ES.on('assign_matcher', function(info){

        console.log('ES is assigning a matcher'); // this does trigger

        var matcher = new Matcher(info);

        //Assign matcher address to the socket
        socket_Matcher = io.connect('http://' + String(matcher.address) + ':' + String(matcher.port));
        }
    });

    socket_Matcher.on('connection_reply', function(message){
        console.log('matcher replied with message: ' + message); // this doesn't trigger 
    });
</script>

匹配码

const http = require('http').createServer();

//for clients
var io = require('socket.io')(http, {cors: {origin: "*"}});

 // for ES
var io_ES = require('socket.io-client')("http://localhost:3000");

var myInfo = new MatcherInfo(-1, 'localhost', 9000, new Position(0, 0));

// Connecting to Entry Server
io_ES.on('connect', function(){
console.log("connected to ES");

io_ES.on('join_info', function(tempID){
    console.log('ES is asking for info');
    if (myInfo.id == -1){
        myInfo.id = tempID;
        io_ES.emit('matcher_join', myInfo);
    }
});

//handle a client connection
io.on('connection', function(socket){
    var message = "client jointed";
    socket.emit('reply', message);

    console.log("client joined"); //this triggers.

    socket.on('example', function(data){
        console.log("event captured"); //arbitrary events get triggered.
    });
});

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题