如何断开网络套接字?

时间:2019-01-08 11:09:47

标签: reactjs sockets websocket socket.io react-redux

我正在使用socket.io-client连接websocket

>>> for filename in glob.glob(os.path.join("/home/sysmgt/rmlogs/January/"*.*"/*.txt")):
...     shutil.copy(filename, "/scratch/rm_logs/")

在成功调用api之后,我正在打开Web套接字,并且能够连接到套接字并获取数据,

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'

套接字成功连接后,我试图像下面这样从import socketIOClient from "socket.io-client"; 断开套接字

_dashboardStoreChange(type){
  if (type == 'SingleDashboard') {
        let singledashboard = DashboardStore._getSingleDashboard() || {};
        this.setState({ singledashboard }, ()=>{
          this.setState({
            dashboardName: this.state.singledashboard.data.dashboard_name,
           }, ()=>{
            let ns = '/dashboard';
            let access_token = localStorage.getItem("auth_token");
            let user_id = localStorage.getItem("user_id")+ +new Date();
            let query_data = {access_token : access_token, user_id: user_id};


            const socket = socketIOClient('http://192.168.0.57:9000'+ns,{query:query_data});
            socket.on("dashboard_data", data => this.setState({ socketresponse: data }, ()=>{
              localStorage.setItem("connected_socket_id", this.state.socketresponse.connected_socket_id);
            }));



            let chart_query_data = {"access_token":access_token, 'user_id' : user_id, dashboard_id: this.state.dashboard_id}
            socket.emit('fetch_graph_data', chart_query_data);

            socket.on('dashboard_data', data => this.setState({response: data}, ()=>{

            }));
          });

        });

     }

}

但是当我再次使用套接字API时,另一个套接字被打开了,而没有调用我如何断开连接。

就像使用componentWillUnmount的{​​{1}}变量一样,我正在调用套接字api。 调用componentwillunmount之后,我需要断开套接字。

谢谢。

2 个答案:

答案 0 :(得分:1)

  

您必须使用socket.disconnect()socket.close()

您可以在文档here.

中了解有关断开连接和连接的更多信息。

以下是用于保存套接字状态的代码,以便您以后可以使用它进行调用。

componentDidMount(){
   this.initSocket();
}

initSocket() {
   const socket = socketIOClient(ENTER SOCKET URL HERE);

   socket.on('connect', () => {
      console.log("Connected");
    });

   this.setState({ socket });
}

使用socket from状态调用.disconnect函数

const { socket } = this.state;
socket.disconnect();

如果您要在其他组件中调用断开连接功能,则可以通过props或redux将套接字从状态传递出去

答案 1 :(得分:0)

您是否尝试使套接字成为组件类的属性?

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.socket = SocketIOClient('http://192.168.0.57:9000'+ns,{query:query_data});
   }
  // some other code...

  compomnentWillUnmount() {
    this.socket.disconnect();
  }
}