Client:
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <MetaCharSet= "Utf-8" />5 <title>Websoket</title>6 </Head>7 <Body>8 <H1>Chat</H1>9 <inputtype= "text"ID= "MSG" />Ten <ButtonID= "Send">Send</Button> One <Scripttype= "Text/javascript"> A varWebSocket= NewWebSocket ("ws://localhost:6666/"); - - functionshowmsg (str) { the varDiv=Document.createelement ('Div'); - div.innerhtml=str; - Document.body.appendChild (Div) - } + - Websocket.onopen=function(){ + Console.log ("Open"); A document.getElementById ('Send'). onclick= function() { at vartxt=document.getElementById ('msg'). Value; - if(TXT) { - websocket.send (TXT); - } - } - } in Websocket.onclose= function() { - Console.log ("Close"); to } + Websocket.onmessage= function(e) { - Console.log (e.data); the showmsg (e.data); * } $ </Script>Panax Notoginseng </Body> - </HTML>
Server-side (node. js):
1 varWS = Require ("Nodejs-websocket")2 3 varPort = 6666;4 5 varClientcount = 0;6 7 varServer = Ws.createserver (function(conn) {8Console.log ("New connection")9clientcount++TenConn.nickname = "User" +Clientcount OneBroadcast ("*******" +conn.nickname + "comes in *******"); A - -Conn.on ("Text",function(str) { theConsole.log ("Received" +str) -Broadcast (Conn.nickname + "say:" +str) - }) - + -Conn.on ("Close",function(code, reason) { +Broadcast ("*******" + Conn.nickname + "left *******"); A }) atConn.on ("Error",function(err) { -Console.log ("Error:" +err); - }) - }). Listen (port) - -Console.log ("WebSocket Server listening on" +port); in - functionBroadcast (str) { toServer.connections.forEach (function(connection) { + connection.sendtext (str) - }) the}
Implement a simple chat room function with WebSocket