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

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

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

  1. <script src="/socket.io/socket.io.js"></script>
  2. <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
  3. <script>
  4. $(function () {
  5. var socket_ES = io.connect("http://localhost:3000");
  6. var socket_Matcher = io(); // Matcher is not yet assigned
  7. // ES asking for info, reply with myInfo
  8. socket_ES.on('join_info', function(msg) {
  9. socket_ES.emit('client_join', myInfo);
  10. });
  11. //ES is giving client the matcher info
  12. socket_ES.on('assign_matcher', function(info){
  13. console.log('ES is assigning a matcher'); // this does trigger
  14. var matcher = new Matcher(info);
  15. //Assign matcher address to the socket
  16. socket_Matcher = io.connect('http://' + String(matcher.address) + ':' + String(matcher.port));
  17. }
  18. });
  19. socket_Matcher.on('connection_reply', function(message){
  20. console.log('matcher replied with message: ' + message); // this doesn't trigger
  21. });
  22. </script>

匹配码

  1. const http = require('http').createServer();
  2. //for clients
  3. var io = require('socket.io')(http, {cors: {origin: "*"}});
  4. // for ES
  5. var io_ES = require('socket.io-client')("http://localhost:3000");
  6. var myInfo = new MatcherInfo(-1, 'localhost', 9000, new Position(0, 0));
  7. // Connecting to Entry Server
  8. io_ES.on('connect', function(){
  9. console.log("connected to ES");
  10. io_ES.on('join_info', function(tempID){
  11. console.log('ES is asking for info');
  12. if (myInfo.id == -1){
  13. myInfo.id = tempID;
  14. io_ES.emit('matcher_join', myInfo);
  15. }
  16. });
  17. //handle a client connection
  18. io.on('connection', function(socket){
  19. var message = "client jointed";
  20. socket.emit('reply', message);
  21. console.log("client joined"); //this triggers.
  22. socket.on('example', function(data){
  23. console.log("event captured"); //arbitrary events get triggered.
  24. });
  25. });

暂无答案!

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

相关问题