所以我刚接触 socket-io 并做出反应,我使用 express 作为后端。我使用的 socket.io-client 版本是 3.0.3。我在后端使用的 socket-io 包的版本也是 3.0.3,服务器连接到通过原始 html 套接字给出的其他请求,但它没有与 react socket.io-client 连接。
客户端:
import './App.css';
import {MainComponent} from "./Components/MainComponent"
import {BrowserRouter as Router} from "react-router-dom";
import openSocket from "socket.io-client";
const socket = openSocket("http://localhost:5000");
function App() {
socket.on("chat", message => {
console.log(message);
});
return (
<div className="App">
<Router>
<MainComponent></MainComponent>
</Router>
</div>
);
}
export default App;
服务器端:
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const Chats = require("./model")
mongoose.connect("mongodb://localhost/chats",{useNewUrlParser:true});
const db = mongoose.connection;
io.on("connection",(socket)=>{
console.log("user has connected")
io.emit("chat","hellow world");
socket.on("join-room",(room)=>{
Chats.find({},(err,data)=>{
if(err) throw err;
socket.emit("load-messages",data)
})
})
socket.on("message",(data)=>{
socket.join(data.room);
io.to(data.room).emit("serverMessage",{message:data.message,user:data.user})
const newChat = new Chats({message:data.message,user:data.user,room:data.room})
newChat.save();
})
})
app.use(cors())
app.use(bodyParser.json());
app.use(express.static("public"))
app.get("/",(req,res)=>{
res.sendFile("index.html")
})
app.get("/chats",(req,res)=>{
Chats.find({},(err,data)=>{
if(err) throw err;
res.json(data)
})
})
http.listen(5000,()=>{
console.log("the server is up and running in the port 5000")
})
将客户端的第 5 行更改为以下内容:
const socket = openSocket("http://localhost:5000", {transports: ['websocket']});
在服务器端更改以下行
io.emit("chat","hellow world");
对此
socket.emit("chat","hellow world");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句