简体   繁体   English

尝试使用socket.io时出现错误

[英]getting an error when trying to use socket.io

I am currently working with socket.io swift client. 我目前正在使用socket.io swift客户端。 Running on Iphone SE. 在Iphone SE上运行。 this is the swift code 这是快速代码

 let socket = SocketIOClient(socketURL: URL(string: "http://example.com:4000")!, config: [.log(true), .forcePolling(true)]);
        socket.connect();
        socket.on("connect") {data, ack in
            print("socket is connected");
            socket.emit("getData", ["data": 3]);
        }

And on the server: 在服务器上:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
    socket.on('getData', function(result){
        console.log(result);
    });
});


app.listen(4000, function () {
  console.log(' on at 4000!');
});

...And on the Xcode console, I get ...然后在Xcode控制台上,我得到

2016-09-29 16:38:33.871895 proj[3070:1019256] LOG SocketEngine: Handshaking
2016-09-29 16:38:33.872301 proj[3070:1019256] LOG SocketEnginePolling: Doing polling request
2016-09-29 16:38:34.004312 proj[3070:1019256] LOG SocketEnginePolling: Got polling response
2016-09-29 16:38:34.004874 proj[3070:1019283] LOG SocketEngine: Got message: Cannot GET /socket.io/?transport=polling&b64=1
2016-09-29 16:38:34.005283 proj[3070:1019283] ERROR SocketIOClient: Got unknown error from server Cannot GET /socket.io/?transport=polling&b64=1

Which demonstrates a connection is made and the server is successfully found, but something else is wrong. 这表明已建立连接并成功找到了服务器,但其他地方有问题。 Would appreciate any help. 将不胜感激。

(Sidenote: If you don't need support for old browsers (or any browsers for that matter, since your client is a native mobile app) then you may consider using WebSocket which is an open standard. Socket.io is usually used to have a WebSocket-like functionality on browsers that don't support WebSocket. WebSocket on the other hand is an open standard, has a wide support (not only in browsers) and it has a better performance. See this answer for more details.) (旁注:如果您不需要旧浏览器(或其他任何浏览器,因为您的客户端是本机移动应用程序)的支持,则可以考虑使用WebSocket,这是一种开放标准。Socket.io通常用于不支持WebSocket的浏览器上的类似于WebSocket的功能;另一方面,WebSocket是开放标准,具有广泛的支持(不仅在浏览器中)而且性能更好。有关更多详细信息,请参见此答案 。)

Now, since you are already using Socket.io then here is how you can diagnose the problem. 现在,由于您已经在使用Socket.io,因此可以通过以下方法诊断问题。 I would try to connect from a browser, which is a main way to connect with Socket.io, and see if that works. 我将尝试从浏览器进行连接,这是连接Socket.io的主要方法,并查看其是否有效。 If it doesn't then it would mean that there's a problem in your server code. 如果没有,那意味着您的服务器代码有问题。 If it does then it could mean that there's a problem in your client. 如果这样做,则可能意味着您的客户有问题。 That would be the first thing to check. 那将是要检查的第一件事。 Going from there you can narrow the problem and hopefully fix it. 从那里可以缩小问题范围,并有望解决它。

If you want to have a starting point with some working code using Socket.io, both server-site (Node.js) and client-side (browser vanilla JavaScript), then you can see the examples that I wrote originally for this answer , that are available on GitHub and on npm : 如果您想以使用Socket.io的一些工作代码作为起点,包括服务器站点(Node.js)和客户端(浏览器原始JavaScript),那么您可以看到我最初为该答案编写的示例, 在GitHubnpm 上可用

Socket.IO Server Socket.IO服务器

Socket.IO server example using Express.js: 使用Express.js的Socket.IO服务器示例:

var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
  console.error('socket.io connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
console.error('socket.io example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js 来源: https : //github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js

Socket.IO Client Socket.IO客户端

Socket.IO client example using vanilla JavaScript: 使用原始JavaScript的Socket.IO客户端示例:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening socket.io connection');
var s = io();
s.on('connect_error', function (m) { log("error"); });
s.on('connect', function (m) { log("socket.io connection open"); });
s.on('message', function (m) { log(m); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.html 来源: https : //github.com/rsp/node-websocket-vs-socket.io/blob/master/si.html

You can compare the same code with WebSocket versions: 您可以将相同的代码与WebSocket版本进行比较:

WebSocket Server WebSocket服务器

WebSocket server example using Express.js: 使用Express.js的WebSocket服务器示例:

var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
  console.error('websocket connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js 来源: https : //github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js

WebSocket Client WebSocket客户端

WebSocket client example using vanilla JavaScript: 使用普通JavaScript的WebSocket客户端示例:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html 来源: https : //github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html

I hope this can help you evaluate whether staying with Socket.io or going with WebSocket is the right decision for you, and will give you some working client-side code to test your backend. 我希望这可以帮助您评估是使用Socket.io还是使用WebSocket是适合您的正确决定,并会为您提供一些有效的客户端代码来测试您的后端。 The code is released under the MIT license (open source, free software) so feel free to use it in your project. 该代码是根据MIT许可 (开源,免费软件)发布的,因此可以在您的项目中随意使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM