套接字IO未连接到正确的服务器

Socket IO not connecting to the right server.

本文关键字:服务器 IO 连接 套接字      更新时间:2023-10-19

我刚刚开始学习node,已经从互联网上拼凑出了一些零碎的东西。我想使用node的一件事是SendGrid从客户端发送电子邮件。我通过在socket.io客户端手动输入socket = io.connect(http://localhost:8080);(就像大家说的那样)来完成这项工作。在我去heroku或类似的服务上主持之前,这在当地一直很好。

以下是我的服务器代码的样子(下面的函数无关紧要,因为它们只是运行sendgrid填充:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// This is the socket.io port. I want the client to go through this.
server.listen(8080);
// this is used to serve a static html page in the public folder.
// I feel like the way I have this set up is part of the issue
app.set('port', (5000));
app.use(express.static(__dirname + '/public'));
app.listen(app.get('port'), function() {
    console.log('Node app is running on port ' + app.get('port'));
});

我去地址http://localhost:5000以查看服务器的html。

这是我编写的客户端代码:

// Init the socket
socket = io.connect('http://localhost');
// send stuff through it. this stuff doesnt matter. but it sends values
// Via json to the server to then use in an email.
socket.emit('sendCompile', {adr: receptients, bod: body });

这给了我一个错误:

socket.io-1.4.5.js:1 GET 
http://localhost/socket.io/?   
EIO=3&transport=polling&t=LFC_cxO 

如有任何帮助,我们将不胜感激。(我已经为此工作了5个多小时:D)

附言:我已经试过像其他人想的那样将其更改为socket = io();socket = io.connect();。但这两种方法都不起作用。我觉得这是我如何编写服务器的问题,因为我只是在找到它们时把它们拼凑在一起。

您需要将域从localhost更改为您的网站,并添加端口,例如:

socket = io.connect('http://localhost');

应该成为

socket = io.connect('http://mywebsite.com:8080');

还要注意,您用于套接字的端口需要打开——如果端口没有打开,您将遇到更多问题。