1. 程式人生 > >使用nodejs-websocket 20行程式碼實現簡單聊天室

使用nodejs-websocket 20行程式碼實現簡單聊天室

安裝nodejs-websocket:

npm install nodejs-websocket

index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>websocket</title>
	</head>
	<body>
		<h1>簡單聊天室</h1>
		<input id="sendTxt" type="text" />
		<button id="sendBtn">傳送</button>
		<div id="recv"></div>
		<script type="text/javascript">
			var websocket = new WebSocket("ws://127.0.0.1:3000/demo2/wsServer.js");
			
			function showMassage(str){
				var div = document.createElement('div');
				div.innerHTML = str;
				document.body.appendChild(div);
			}
			websocket.onopen = function () {
				console.log('websocket open');
				document.getElementById("sendBtn").onclick = function () {
					var txt = document.getElementById("sendTxt").value;
					if(txt){
						websocket.send(txt);
					}
				}
			}
			websocket.onclose = function () {
				console.log('websocket close');
			}
			websocket.onmessage = function (e) {
				console.log(e.data);
				showMassage(e.data);
			}
			
		</script>
	</body>
</html>

wsServer.js

var ws = require("nodejs-websocket")
var PORT = 3000
var clientCount = 0
// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
	console.log("New connection")
	clientCount++;
	conn.nickname = 'user' + clientCount;
	broadcast(conn.nickname + 'comes in');
	conn.on("text", function (str) {
		console.log("Received "+str)
		broadcast(conn.nickname + ':' + str);
	})
	conn.on("close", function (code, reason) {
		console.log("Connection closed")
		broadcast(conn.nickname + 'left');
	})
	conn.on("error", function (err) {
		console.log("Hand error")
		console.log(err)
	})
}).listen(PORT)

console.log("WebSocket server listening on port " + PORT);

function broadcast(str){
	server.connections.forEach(function(connection){
		connection.sendText(str);
	});
}

效果: