node.js + websocket
官方教程是用express搭的服务器,教程其实很清楚,但是不知道为什么我报错了,好像是引入那个juery包失败
- 安装npm install nodejs-websocket --save
- 直接在visual stdio终端执行就可以
chat.html
<!DOCTYPE html>
<html lang=‘en‘>
<head>
<meta charset=‘UTF-8‘/>
<meta name="viewport" content = "width=divice-width,initial-scale=1.0"/>
<title>Socket.IO chat</title>
<style>
div{
width:800px;
height:500px;
background-color: bisque;
border: darkkhaki;
}
button { width: 9%; background: darksalmon; border: none; padding: 10px; }
</style>
</head>
<body>
<input type = ‘text‘ placeholder="请输入你的内容" />
<button>Send</button>
<div></div>
</body>
</html>
<script>
var div = document.querySelector(‘div‘)
var button = document.querySelector(‘button‘)
var input = document.querySelector(‘input‘)
//有了自己的server,就可以连接自己的server ws://echo.websocket.org
var socket = new WebSocket(‘ws://localhost:3000‘);
socket.addEventListener(‘open‘,function(){
div.innerHTML = ‘连接成功‘
})
button.addEventListener(‘click‘,function(){
var value = input.value;
socket.send(value)
})
socket.addEventListener(‘message‘,function(e){
console.log(e.data)
div.innerHTML = e.data
})
socket.addEventListener(‘close‘,function(){
div.innerHTML = ‘服务断开连接‘
})
</script>
server.js
//导入node.js-websocket
const ws = require(‘nodejs-websocket‘)
const PORT = 3000
//创建一个server
//每次有用户连接,函数就会被执行,就会给用户创造一个连接对象
const server = ws.createServer(connect => {
console.log("an user connected.")
connect.on(‘text‘,data => {
//我个人感觉,这个server.js就是自己实现那个url实现的功能
console.log("接收到了用户的数据",data)
connect.send(data)
//connect.send(data.toUpperCase()+"!!!")
})
connect.on(‘close‘,() => {
console.log("连接断开了")
})
connect.on(‘error‘,() => {
console.log("用户连接异常")
})
})
server.listen(PORT,() => {
console.log(‘websocket启动成功‘)
})