我正在尝试创建客户端-服务器Web套接字应用程序,但似乎无法连接客户端和服务器端。
我尝试了其他类似的问题,例如here,但都没有起作用。
我已经使用Express Generator设置了Express。
//app.js Server side
//it's running on port 4000
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const http = require('http');
const socketIO = require('socket.io');
const indexRouter = require('./routes/index');
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use(cors());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Methods',
'OPTIONS, GET, POST, PUT, PATCH, DELETE'
);
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.use('/', indexRouter);
io.on('connection', socket => {
console.log('user connected');
});
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
这是我的客户端代码
//client side
import React, { Component } from 'react';
import socketIOClient from 'socket.io-client';
const socket = socketIOClient.connect('http://localhost:4000');
class Posts extends Component {
componentDidMount = () => {
console.log(socket);
socket.on('connect', () => console.log('Socket is connected'));
};
render() {
return (
<div }>
//codes
</div>
);
}
}
export default Posts;
componentDidMount内部套接字的输出是
_callbacks: Object { "$connecting": (1) […], "$connect": (2) […] }
acks: Object { }
connected: false
disconnected: true
flags: Object { }
ids: 0
io: Object { _reconnection: true, _reconnectionDelay: 1000, _reconnectionDelayMax: 5000, … }
json: Object { nsp: "/", ids: 0, connected: false, … }
nsp: "/"
receiveBuffer: Array []
sendBuffer: Array []
subs: Array(3) [ {…}, {…}, {…} ]
<prototype>: Object { addEventListener: addEventListener(), on: addEventListener(), once: once(), … }
我希望在服务器端安装一个控制台:“用户已连接” 但我找不到404。
我正在使用
"socket.io": "^2.2.0",
"react": "^16.8.6",