I thought the purpose of web sockets was to support the socket client running in the browser. When I run this client code in the browser I get a message saying ws does not work in the browser.
Жыл бұрын
Hi, Steve! That's right, the ws library works on Node.js for server and client code but won't work in the browser. There's native WebSocket support in browsers today. Take a look at these Mozilla docs on How to write WebSocket client apps › developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications Here's a sample code to connect to a server from a browser client, log received messages to the console, and send a message to the server when we connect. ``` // Create a WebSocket client in the browser. const ws = new WebSocket("ws://localhost:1234"); // Log incoming messages to the console. ws.onmessage = function (event) { // This runs when receiving message. console.log(event.data); }; ws.onopen = () => { // This runs when we connect. // Submit a message to the server ws.send(`Hello, WebSocket! Sent from a browser client.`); }; ``` Permalink › nono.ma/e/Q2D I hope this helps! Kindly, Nono
@damcism Жыл бұрын
Thanks for a great video. In which moment does it actually connect? This is a bit weird because you don't run anything like ws.connect() and the open event is triggered. That suggests that it opens the connection when you initialize new object, but at that moment you haven't defined "on open" event, so that shouldn't work then...
Жыл бұрын
Hi, damcism! Thanks for your comment. Did you check the server code video? kzbin.info/www/bejne/nmalYZyFr52pjMk In client.ts, the following line is all you need to create a client and connect to the server. const ws = new WebSocket(`ws://localhost:${port}`); Even when you define the "open" and "message" handlers afterwards, they work with the same connection, probably because the definition of those handlers happens really fast, before the connection with the server has been established. I hope this helps! Kindly, Nono
@chirkov Жыл бұрын
Where is TypeScript?
Жыл бұрын
Hi, Chikov! The moment you install the typescript @types/node and @types/ws packages for development (with the command below) you get TypeScript type completion for free. npm install --save-dev typescript @types/node @types/ws I hope that helps! Kindly, Nono
@AustinAtchley11 ай бұрын
Very clear. Thanks for the video
11 ай бұрын
Thanks so much for you comment, Austin. I'm glad you found this video useful. Nono