Nodejs webSocket test

2621 ワード

今日はwebsocketの関連実現をちょっと見ました.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript"> var ws=new WebSocket("ws://localhost:3004"); ws.onopen = function(){ ws.send("hello"); } ws.onmessage = function(msg){ console.log(msg.data); } </script>
</head>
<body>
</body>
</html>
Nodejs server
var WebSocketServer = require('ws').Server
    , wss = new WebSocketServer({port:3004});


wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        console.log('received:%s', message);
    });
    ws.send('I am a message sent from a ws server');
});
以上