注意:需要后台发送数据,或者使用node的pm2自拟后台
websocket安装:
npm i ws -S
react中使用的代码:
import React from 'react'
import './styles.less'
import { Action } from '../../../node_modules/rxjs/internal/scheduler/Action';
export default class Home extends React.Component {
constructor (props) {
super(props)
this.ws = new WebSocket("ws://localhost:8181")
this.WebSocketTest()
}
state = {
name: '',
}
WebSocketTest = () => {
if ('WebSocket' in window) {
// 打开一个 web socket
this.ws.onopen = () => {
// Web Socket 已连接上,使用 send() 方法发送数据
this.ws.send('发送数据')
console.log("数据发送中...")
}
this.ws.onmessage = evt => {
var received_msg = evt.data
console.log(received_msg, '333333333')
}
this.ws.onclose = () => {
// 关闭 websocket
console.log("连接已关闭...")
}
}
}
onSend = () => {
this.ws.send('发送数据')
}
render () {
return (
<div className="pages-home">
<button onClick={this.onSend}>sorket</button>
</div>
)
}
}