서버: index.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws, request) {
console.log('connection');
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.on('close', function close(code, reason) {
console.log('close ' + code + ':'+reason);
});
ws.send('something');
});
클라이언트: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Native WebSocket Example</title>
</head>
<body>
<script>
// 웹소켓 전역 객체 생성
var ws = new WebSocket("ws://localhost:8080", "echo-protocol");
// 연결이 수립되면 서버에 메시지를 전송한다
ws.onopen = function(event) {
ws.send("Client message: Hi!");
}
// 서버로 부터 메시지를 수신한다
ws.onmessage = function(event) {
console.log("Server message: ", event.data);
document.write("Server message: ", event.data);
}
// error event handler
ws.onerror = function(event) {
console.log("Server error message: ", event.data);
}
</script>
</body>
</html>