程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何让我的 websocket 服务器和客户端支持多个房间?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何让我的 websocket 服务器和客户端支持多个房间??

开发过程中遇到如何让我的 websocket 服务器和客户端支持多个房间?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何让我的 websocket 服务器和客户端支持多个房间?的解决方法建议,希望对你解决如何让我的 websocket 服务器和客户端支持多个房间?有所启发或帮助;

我在 YouTube https://www.youtube.com/watch?v=LenNpb5zqGE&t=322s 上学习了一个教程。

我最终让一切都按预期工作。我唯一需要的就是房间。

每当我访问这样的网址时:www.example.com/chat/room1 我应该加入这个房间并且只能在这里发送和接收。

目前,每当我访问网站内的任何网址时,我都会在同一个房间里结束。我应该只能加入带有 /chat/roomname 网址的聊天室。

这是服务器代码:

import ReactDOM from "react-dom";
import React,{ Component } from "react";
import { w3cwebsocket as W3CWebSocket } from "websocket";
import { Card,Avatar,input,Typography } from "antd";
import "antd/dist/antd.CSS";
import "./index.CSS";

const { Search } = input;
const { Text } = Typography;
const { Meta } = Card;

const clIEnt = new W3CWebSocket("ws://127.0.0.1:8000");

export default class App extends Component {
state = {
username: "",isLoggedIn: false,messages: [],};

onbuttonClicked = (value) => {
clIEnt.send(
  JsON.Stringify({
    type: "message",room: window.LOCATIOn.pathname,msg: value,user: this.state.username,})
);
this.setState({ searchVal: "" });
};
componentDIDMount() {
clIEnt.onopen = () => {
  console.log("WebSocket ClIEnt Connected");
};
clIEnt.onmessage = (messagE) => {
  const dataFromServer = JsON.parse(message.data);
  console.log("got reply! ",dataFromServer);
  if (dataFromServer.type === "message") {
    this.setState((statE) => ({
      messages: [
        ...state.messages,{
          msg: dataFromServer.msg,user: dataFromServer.user,},],}));
  }
};
}
render() {
return (
  <div classname="main" ID="wrapper">
    {this.state.isLoggedIn ? (
      <div>
        <div classname="title">
          <Text
            ID="main-heading"
            type="secondary"
            style={{ FontSize: "36px" }}
          >
            Websocket Chat: {this.state.usernamE}
          </Text>
        </div>
        <div
          style={{
            display: "flex",flexDirection: "column",paddingBottom: 50,}}
          ID="messages"
        >
          {this.state.messages.map((messagE) => (
            <Card
              key={message.msg}
              style={{
                wIDth: 300,margin: "16px 4px 0 4px",alignSelf:
                  this.state.username === message.user
                    ? "flex-end"
                    : "flex-start",}}
              loading={falsE}
            >
              <Meta
                avatar={
                  <Avatar
                    style={{ color: "#f56a00",BACkgroundcolor: "#fde3cf" }}
                  >
                    {message.user[0].toupperCase()}
                  </Avatar>
                }
                title={message.user + ":"}
                description={message.msg}
              />
            </Card>
          ))}
        </div>
        <div classname="bottom">
          <Search
            placeholder="input message and send"
            enterbutton="Send"
            value={this.state.searchVal}
            size="large"
            onChange={(E) => this.setState({ searchVal: e.target.value })}
            onSearch={(value) => this.onbuttonClicked(value)}
          />
        </div>
      </div>
    ) : (
      <div style={{ padding: "200px 40px" }}>
        <Search
          placeholder="Enter Username"
          enterbutton="Login"
          size="large"
          onSearch={(value) =>
            this.setState({ isLoggedIn: true,username: value })
          }
        />
      </div>
    )}
  </div>
);
}
}

ReactDOm.render(<App />,document.getElementByID("root"));

这是客户端代码:

const webSocketsServerPort = 8000;
const webSocketServer = require("websocket").server;
const http = require("http");

// Spinning the http server and the websocket server.
const server = http.createServer();
server.Listen(webSocketsServerPort);
console.log("Listening on port 8000");

const clIEnts = {};

const wsServer = new webSocketServer({
  httpServer: server,});

// This code generates unique userID for everyuser.
const getUniqu@R_197_11534@ = () => {
const s4 = () =>
Math.floor((1 + Math.random()) * 0x10000)
  .toString(16)
  .subString(1);
return s4() + s4() + "-" + s4();
};

wsServer.on("request",function (request) {
  var userID = getUniqu@R_197_11534@();
  console.log(
  new Date() +
  " RecIEved a new connection from origin " +
  request.origin +
  "."
);

// You can rewrite this part of the code to accept only the requests from allowed origin
const connection = request.accept(null,request.origin);
clIEnts[userID] = connection;
console.log(
"connected: " + userID + " in " + Object.getownPropertynames(clIEnts)
);

connection.on("message",function (messagE) {
if (message.type === "utf8") {
  console.log("Received message: ",message.utf8Data);

  // broadcasTing message to all connected clIEnts
  for (key in clIEnts) {
    clIEnts[key].sendUTF(message.utf8Data);
    console.log("sent message to: ",clIEnts[key]);
  }
}
});
});

提前致谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

大佬总结

以上是大佬教程为你收集整理的如何让我的 websocket 服务器和客户端支持多个房间?全部内容,希望文章能够帮你解决如何让我的 websocket 服务器和客户端支持多个房间?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。