【发布时间】:2021-11-10 20:31:03
【问题描述】:
我有一个如下所示的服务器代码:
import express, { Response } from "express";
import { Server, Socket } from "socket.io";
import { createServer, Server as S } from "http";
// import router from "./routes";
// ----
const app: express.Application = express();
// app.use(router);
app.get("/", (_req: any, res: Response) =>
res.status(200).sendFile(__dirname + "/index.html")
);
const PORT: any = 3001 || process.env.PORT;
const server: S = createServer(app);
const io = new Server(server, {});
io.on("connection", (socket: Socket) => {
console.log("we have a new connection");
console.log(socket.id);
});
//
server.listen(PORT, () => {
console.log(`The server is running on port: ${PORT}`);
});
在我的index.html 这是我的代码:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
当我在 http://localhost:3001 访问网络时,我得到控制台日志,socket.io 正在侦听新连接。我想要的是使用socket.io-client 和在端口 3000 上运行的反应服务器。这是我尝试过的:
import io from "socket.io-client";
const client = io("http://localhost:3001/").connect();
const App: React.FC<{}> = () => {
return (
<div className="app">
<h1>Socket.io</h1>
</div>
);
};
当我访问 http://localhost:3000 时,屏幕上没有任何记录,可能是什么问题?
【问题讨论】:
标签: node.js reactjs sockets socket.io