簡體   English   中英

在類外部調用函數與在內部調用函數有什么區別?

[英]What is the difference between invoking a function outside of class vs inside of it?

客戶端上的套接字事件遇到一些意外的功能。 我有兩個客戶加入socket.io會議室。 它們已成功加入,如我的服務器控制台日志中所示。 在客戶端,該事件已成功發送並被服務器成功接收。 服務器正在向會議室中的兩個客戶端,發送方和另一個客戶端發送事件。 只有發送客戶端收到第一次嘗試。 在所述半失敗嘗試之后,如果另一個客戶端嘗試相同的套接字發射,則服務器成功發送到兩個客戶端。 .emit().on()在組件函數中。

有趣的是 ,如果將服務器事件的.on()放置在類之外 ,則一切在第一次時都可以正常工作。

零件:

import stuff
const socket = io("http://172.**.**.***:3000");
// example '.on()' that works correctly
socket.on("test", () => {
  alert("response from outside component");
});
export default class Lobby extends React.Component {
  constructor() { }
  onTest(socket) {
    alert("outgoing alert");
    socket.emit("test", {
      room: this.state.room
    });
    // '.on()' that doesn't work correctly
    socket.on("test", () => {
      alert("incoming client alert")
    });
  }
  render() {
    <View>
      <TouchableOpacity onPress={() => this.onTest(socket)}>
        <Text>Press me </Text>
      </TouchableOpacity>
    </View> 
  }

服務器事件:

io.on("connection", socket => {
  console.log("user connected with socket id:" + socket.id);
  socket.on("test", test => {
    console.log(received from client, emitting to room #:" + test.room);
    io.to(test.room).emit("test");
  });
}

原因還沒有發送任何東西的客戶, omTest尚未調用,從而socket.on("test", ...)不執行和不加處理,因此,沒有一個是處理傳入的消息,好像沒有到達。 設置套接字時,應始終直接附加處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM