我尝试使用[socket.io-client][1]和我在react应用程序中添加的以下代码将数据从客户端发送到服务器。
import io from "socket.io-client";
var socket = io.connect('http://localhost:3002');
socket.emit("room", 'room1');
并且在服务器端添加了
const app = express();
const http = require("http").Server(app);
const io = require("socket.io");
var socket = io(http);
socket.on("connection", socket => {
console.log("user connected");
socket.on('room', function(room){
console.log("room", room);
socket.join(room);
});
});
app.listen(3002);
但是,我在服务器端没有收到任何数据,即使是从服务器到客户端建立和发送的套接字连接也运行良好。非常感谢。[1] :https://www.npmjs.com/package/socket.io-client
您正在创建express服务器,但从未告诉它在端口上侦听。
你需要像这样添加app.listen((:
const app = express();
const http = require("http").Server(app);
app.listen(3002);
const io = require("socket.io");
var socket = io(http);
socket.on("connection", socket => {
console.log("user connected");
socket.on('room', function(room){
console.log("room", room);
socket.join(room);
});
});