[英]Socket.io not recognizing connect event
I am trying to learn socket.io and integrate it into an electron app.我正在尝试学习 socket.io 并将其集成到 electron 应用程序中。 I am trying to just get the connect event to trigger.
我试图让连接事件触发。 It is fairly straightforward and I have ran through the code many times but have not found the issue.
这相当简单,我已经多次运行代码但没有发现问题。
Nothing gets printed to the console when I connect to localhost当我连接到 localhost 时,没有任何内容打印到控制台
const http = require('http');
const server = http.createServer(function (req, res){
res.writeHead(200);
res.end('test');
});
server.listen(8080);
const socket = require('socket.io')(server);
console.log('server on');
socket.on('connection', (socket) => {
console.log('user connected');
console.log(socket);
});
You need to connect to this socket on a specific end-point from the client side.您需要从客户端连接到特定端点上的此套接字。
Server Side服务器端
const socketIO = require('socket.io')({path: '/my-first-path'}).listen(server);
socketIO.on('connection', socket => {
console.log('user connected');
socket.on('disconnect', reason => {
console.log('socket disconnected for ', reason);
})
})
Client Side客户端
import io from 'socket.io-client';
let socket = null, serverAddress = 'http://localhost:8080';
socket = io(serverAddress, {
path: '/my-first-path',
query: { name: 'Robin', id: '123' }, // optional
reconnection: true, // optional
reconnectionDelay: 2000 // optional
});
socket.on('connect', () => {
console.log('------SOCKET CONNECTION IS ESTABLISHED------');
socket.on('disconnect', reason => {
console.log(`------SOCKET CONNECTION IS DISCONNECT, ${reason}-------`);
});
});
socket.on('reconnect', () => {
console.log(`------SOCKET CONNECTION IS SUCCESSFULLY RECONNECTED-------`);
});
socket.on('reconnecting', attempt => {
console.log(`------SOCKET CONNECTION IS ATTEMPTING TO RECONNECT-------`);
});
Hope this will helpful.希望这会有所帮助。 If you want, you can create multiple end-point from server and connect to that end-point from client.
如果需要,您可以从服务器创建多个端点并从客户端连接到该端点。 On that case, server and client code will be indentical except the path.
在这种情况下,服务器和客户端代码将是相同的,除了路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.