安装ws:
我们来看一下完整的代码:
服务端:
const WebSocket = require('ws')
const wss = new WebSocket.Server({port:9999})
wss.on('connection', function (ws) {
ws.on('message', function (message) {
console.log('receive data from client:', message)
ws.send('To Client: data received!')
})
})
客户端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>websocket</title>
</head>
<body>
<script>
var ws = new WebSocket('ws://localhost:9999')
ws.onopen = function(evt) {
console.log('Connection Opened!')
ws.send('hello server! i am client!')
}
ws.onmessage = function(evt) {
console.log('I am client')
ws.send('xxxxx')
console.log('receive data from server:', evt)
ws.close()
}
ws.onclose = function() {
console.log('Connection Closed!')
}
</script>
</body>
</html>
服务端打印结果:
客户端浏览器打印结果:
|