套接字。IO客户端如何连接?

时间:2021-02-09 19:42:50

I was following the second example here: https://github.com/socketio/socket.io-client

下面是第二个示例:https://github.com/socketio/socket.io-client

and trying to connect to a website that uses websockets, using socket.io-client.js in node.

尝试连接到一个使用websockets的网站,使用socket.com .io-client。js的节点。

My code is as follows:

我的代码如下:

var socket = require('socket.io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket');

socket.on('connect', function() {
    console.log("Successfully connected!");
});

Unfortunately, nothing gets logged.

不幸的是,没有被记录。

I also tried:

我也试过:

var socket = require('socket.io-client')('http://website.com/');

socket.on('connect', function() {
    console.log("Successfully connected!");
});

but nothing.

但是什么都没有。

Please tell me what I'm doing wrong. Thank you!

请告诉我我做错了什么。谢谢你!

1 个解决方案

#1


3  

Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client.

尽管上面发布的代码应该以另一种方式连接到套接字。io服务器调用客户端上的connect()方法。

Socket.io Client

const io = require('socket.io-client');
const socket = io.connect('http://website.com');

socket.on('connect', () => {
  console.log('Successfully connected!');
});

Socket.io Server w/ Express

const express = require('express');

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

const port = process.env.PORT || 1337;

server.listen(port, () => {
    console.log(`Listening on ${port}`);
});

io.on('connection', (socket) => {
    // add handlers for socket events
});

Edit

Added Socket.io server code example.

套接字。io服务器代码的例子。

#1


3  

Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client.

尽管上面发布的代码应该以另一种方式连接到套接字。io服务器调用客户端上的connect()方法。

Socket.io Client

const io = require('socket.io-client');
const socket = io.connect('http://website.com');

socket.on('connect', () => {
  console.log('Successfully connected!');
});

Socket.io Server w/ Express

const express = require('express');

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

const port = process.env.PORT || 1337;

server.listen(port, () => {
    console.log(`Listening on ${port}`);
});

io.on('connection', (socket) => {
    // add handlers for socket events
});

Edit

Added Socket.io server code example.

套接字。io服务器代码的例子。