Web Sockets
- WebSockets for persistent socket connetion from browser,
starts out as an http connection and then upgrades to
persistent tcp connection. Implemented as an event driven
api for browsers and Node.js. Implemented in other ways for
other platforms as well.
- Using ws, the Node.js
websocket server implementation.
echoServerSimple.js
- The corresponding echoClient.html
Using client side web sockets API
socket = new WebSocket("ws://localhost:8000");
socket.onopen = function (event) {
socket.onclose = function (event) {
event.code
event.reason
event.wasClean
socket.onmessage = function (event) {
event.data
- Note: If you loaded a secure webpage (https), and want to open in insecure
websocket with url line
ws://....
, your browser will complain.
Instead, use wss://....
for a secure connection.
For example...
socket = new WebSocket("wss://localhost:8000"); // for secure connection
- Note: If you want to open a websocket to a host other than
the origin of a webpage, the webpage must allow it. See for example
Access control.
- Same as echoServerSimple.js but everyone gets the message
echoServerBroadcast.js
Note: wss.clients is a collection of clients connected to this server.
add broadcast method to wss (wss.broadcast=...)
- Simple drawing application using the echoServerBroadcast.js
References