后端
安装 webSocket
npm i ws
创建对象
const webSocket
= require('ws')
const wss
= new webSocket.Srever({
port
: 9998
})
监听事件
连接事件
wss
.on("connection", client
=>{
console
.log('有客户端连接。。。')
})
接收数据事件
wss
.on("connection", client
=>{
client
.on("message", msg
=>{
console
.log('客户端发送过来的数据')
})
})
发送数据
client
.send('发送数据给前端端')
示例
const WebSocket
= require('ws')
const wss
= new WebSocket.Server({port
:8889})
wss
.on('connection', client
=>{
client
.on('message', msg
=>{
console
.log('msg',msg
)
client
.send('hello socket backed data')
})
})
前端
创建对象
const ws
= new WebSocket('ws://localhost:9998')
监听事件
连接成功事件
ws
.onopen = function(){}
接收数据事件
ws
.onmessage = function(){}
关闭连接事件
ws
.onclose = function(){}
发送数据
wx
.send()
示例
<!DOCTYPE html
>
<html lang
="en">
<head
>
<meta charset
="UTF-8">
<meta name
="viewport" content
="width=device-width, initial-scale=1.0">
<title
>Document
</title
>
</head
>
<body
>
<button id
="connection">连接 服务端
</button
>
<button id
="send" disabled
>发送数据
</button
>
从服务端接收数据:
<br
>
<span id
='text'></span
>
<script
>
const connection
= document
.getElementById('connection')
const send
= document
.getElementById('send')
const text
= document
.getElementById('text')
let ws
= null
connection
.onclick = function(){
ws
= new WebSocket('ws://localhost:8889')
ws
.onopen = function(){
console
.log('连接成功')
send
.disabled
= false
}
ws
.onmessage = function(msg
){
console
.log('接收数据',msg
.data
)
}
ws
.onclose = function(){
console
.log('断开连接')
send
.disabled
= true
}
}
send
.onclick = function(){
ws
.send('发送数据')
}
</script
>
</body
>
</html
>
转载请注明原文地址: https://lol.8miu.com/read-29531.html