DEV Community

HarmonyOS
HarmonyOS

Posted on

socket.TCPSocketServer subscribes to the 'connect' event. After shutting down, re-subscribing does not take effect

Read the original article:socket.TCPSocketServer subscribes to the 'connect' event. After shutting down, re-subscribing does not take effect

Problem Description

When socket.TCPSocketServer subscribes to the 'connect' event and then turns it off, the callback method does not take effect when it is re-subscribed

Background Knowledge

TCPSocketServer.listen : Binds the IP address and port. The port can be specified or randomly assigned by the system. Listens for and accepts TCPSocket connections established with this socket.
TCPSocketServer.on('connect') : Subscribes to the connection event of TCPSocketServer.

Troubleshooting Process

socket.TCPSocketServer fails after calling on('connect'). The problem code is as follows:

// Enable serverSocket listening
const tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
let bindAddr: socket.NetAddress = {
address: '::',
port: 1111,
family: 2
};
// Set other properties for the TCPSocketServer connection
const options: socket.TCPExtraOptions = {
keepAlive: true,
};
tcpServer.setExtraOptions(options);
tcpServer.listen(bindAddr).then(() => {
console.info(TAG, 'bind address success');
}).catch((err: BusinessError) => {
console.info(TAG, server listen error : ${err.message});
});

// Subscribe to TCPSocketServer events
const connectCallBack = () => {
console.log('test');
};
tcpServer.on('connect', connectCallBack);

tcpServer.off('connect', connectCallBack);
//The callback is no longer effective
tcpServer.on('connect', connectCallBack);
Enter fullscreen mode Exit fullscreen mode

Solution

According to the official website documentation on('connect') , this method can only be called after the listen method is successfully called. Therefore, before re-enabling listening with on('connect'), re-call listen and it will succeed:

tcpServer.listen(bindAddr, (err: BusinessError) => {
  if (err) {
    console.error('listen fail');
    return;
  }
  console.info('listen success');
  tcpServer.on('connect', (data: socket.TCPSocketConnection) => {
    console.info(`connect success: ${JSON.stringify(data)}`)
  });
})
Enter fullscreen mode Exit fullscreen mode

Related Documents or Links

https://developer.huawei.com/consumer/en/forum/topic/0207179055554055441

Written by Simay Ayberik

Top comments (0)