2019年12月3日 星期二

node.js use websocket Chat Room sample

參考:https://www.nodebeginner.org/index-zh-tw.html

1. 開啟PowerShell並安裝
    npm install express       <- 框架
    npm install ws               <- websocket 

2. service.js

const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('open', function open() {
  console.log('connected');
});

server.on('close', function close() {
  console.log('disconnected');
});

server.on('connection', function connection(ws, req) {
  const ip = req.connection.remoteAddress;
  const port = req.connection.remotePort;
  const clientName = ip + port;

  console.log('%s is connected', clientName)

  ws.send("Welcome " + clientName);

  ws.on('message', function incoming(message) {
    console.log('received: %s from %s', message, clientName);
    
    server.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send( clientName + " -> " + message);
      }
    });
  });
});

3. client.html

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
</head>

<body>
<script type="text/javascript">
var socket;
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:8080/ws");
socket.onmessage = function (event) {
var ta = document.getElementById('responseText');
ta.value = ta.value + '\n' + event.data
};
socket.onopen = function (event) {
var ta = document.getElementById('responseText');
ta.value = "connection!";
};
socket.onclose = function (event) {
var ta = document.getElementById('responseText');
ta.value = ta.value + "connection close";
};
} else {
alert("你的浏览器不支持 WebSocket!");
}

function send(message) {
if (!window.WebSocket) {
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("connection fail.");
}
}
</script>
<form onsubmit="return false;">
<h3>WebSocket Chat room:</h3>
<textarea id="responseText" style="width: 500px; height: 300px;"></textarea>
<br>
<input type="text" name="message" style="width: 300px" value="Welcome">
<input type="button" value="Send" onclick="send(this.form.message.value)">
<input type="button" onclick="javascript:document.getElementById('responseText').value=''" 
value="Clean">
</form>
<br>
</body>

</html>

4. 伺服器端啟動service.js
    客戶端透過瀏覽器開啟client.html即可對話

sudo kill $(ps aux | grep 'app.js' | awk '{print $2}') sudo node service.js &

沒有留言: