Socket.IO客户端如何连接? [英] Socket.IO Client How to Connect?

查看:87
本文介绍了Socket.IO客户端如何连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里使用了第二个示例:https://github.com/socketio/socket.io-client

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

并尝试连接到使用 websockets 的网站,在 node 中使用 socket.io-client.js.

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

我的代码如下:

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.

我也试过:

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

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

但什么都没有.

请告诉我我做错了什么.谢谢!

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

推荐答案

虽然上面发布的代码应该可以连接到 socket.io 服务器的另一种方法是调用 connect() 方法客户.

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.

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

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

带 Express 的 Socket.io 服务器

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
});

编辑

添加了 Socket.io 服务器代码示例.

Edit

Added Socket.io server code example.

这篇关于Socket.IO客户端如何连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆