Closed TheWow closed 4 years ago
Let me see your code. I thought that websocket does not still opening the socket. Therefore, this.webSocket is not still initialized.
i want to create class for send data
export class SocketController { async sendSocket(msg: string) { const ws: WebSocket = new WebSocket("ws://192.168.1.1:7001"); ws.on("open", function () { ws.send(
${msg}); }); ws.on("message", function (message: string) { console.log(message); }); // ws.on("close", function () { // }); } }
and user class
SocketController.sendSocket(
{
"event":"process",
"message":${i + 1},
"value":${tonumprocess},
"total":${i + 1}
});
please Recommend
Where did you call isClosed in the code? And you should fix indent format. And I don't know $ syntax.
server.ts file
const wss = new WebSocketServer(7001);
console.log(
`websocket Listening on:https://0.0.0.0:7001`,
);
interface BroadcastObj {
event: string;
message: string;
value: number;
total: number;
}
wss.on("connection", function (ws: WebSocket) {
console.log("socket connected!");
ws.on("message", function (message: string) {
let evObj = JSON.parse(message.toString());
broadcast(evObj);
});
});
const broadcast = function broadcast(msg: BroadcastObj) {
wss.clients.forEach(function each(client) {
client.send(JSON.stringify(msg));
});
};
SocketController.ts file
export class SocketController {
async sendSocket(msg: string) {
const ws: WebSocket = new WebSocket("ws://192.168.1.1:7001");
if (ws.isClosed == true) {
ws.on("close", function () {
console.log("closed connect");
});
} else {
ws.on("open", function () {
ws.send(`${msg}`);
});
ws.on("message", function (message: string) {
console.log(message);
});
}
//console.log(ws.isClosed);
// ws.on("message", function (message: string) {
// console.log(message);
// });
// ws.on("close", function () {
// });
}
}
export default new SocketController();
after run
for (let i = 0; i < totalprocess; i++) {
SocketController.sendSocket(`
{
"event":"process",
"message":${i + 1},
"value":${totalprocess},
"total":${i + 1}
}`);
}
error
error: Uncaught TypeError: Cannot read property 'isClosed' of undefined
return this.webSocket!.isClosed;
^
at WebSocket.get isClosed (websocket.ts:141:28)
at SocketController.sendSocket (SocketController.ts:10:12)
at ProcessController.testsocket (ProcessController.ts:70:24)
please recommend for this i want to create loop send data websocket server to client for update progress bar realtime thanks
You can not use isClosed in the outside of callback such code. isClosed can only be used after ws.on("open"... is called.
like this.
ws.on("open", function () {
console.log(`isClosed: ${ws.isClosed}`);
});
ws.on("close", function () {
console.log("closed connect");
console.log(`isClosed: ${ws.isClosed}`);
});
thanks you
how to check status connected ? help me please this error error: Uncaught TypeError: Cannot read property 'isClosed' of undefined return this.webSocket!.isClosed;