npm 官网中的ws
在koa中引入
import { useEffect, useRef } from 'react'
const Index = () => {
// 输入框
let inp = useRef(null)
// ‘我’发出消息
let aa = useRef(null)
// ‘别人’回我消息
let bb = useRef(null)
// 聊天室接口
let ws = new WebSocket('ws://localhost:8080')
useEffect(() => {
ws.onmessage = (e) => {
console.log(e)
setTimeout(() => {
// 后台回我的消息
aa.current.innerHTML += e.data + '<br/>'
}, 300)
}
ws.onopen = () => {
console.log('连接成功')
}
}, [])
return (
<div style={{ width: '200px', height: '200px' }}>
{/* <div style={{ width: '200px', height: '200px', display: 'flex', justifyContent: 'space-around' }} >
</div> */}
<div style={{ width: '200px', height: '200px' }}>
{/* 后台回消息的显示 */}
<p><span ref={aa} style={{float:'left',border:"1px solid red"}}>
{/* <img src={require('../../accect/77.jpg')} style={{ width: '50px', height: '50px' }}></img> */}
</span>
</p>
<p><span ref={bb} style={{float:'right'}}>
<img src={require('../../accect/77.jpg')} style={{ width: '50px', height: '50px' }}></img></span></p>
</div>
{/* 输入框 */}
<input type='text' ref={inp}></input>
<button onClick={() => (
// 我发送的消息
ws.send(inp.current.value),
bb.current.innerHTML += inp.current.value + '<br/>',
inp.current.value = ''
)}>发送</button>
</div>
)
}
export default Index;
比较规范的排版格式
import React, { useRef } from 'react'
import "./index.css"
function Index() {
let ws = new WebSocket("ws://localhost:8080")
let inp = useRef()
ws.onmessage = (e) => {
console.log(e)
setTimeout(()=>{
let div = document.createElement('DIV')
div.innerHTML = `
<img style="width: 40px; height: 40px;" src='https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' />
<p style="margin: 0px 10px;padding: 10px 30px;border: 1px solid red;">${e.data}</p>
`
div.style.width = "80vw"
div.style.display = "flex"
div.style.alignItems = 'center'
div.style.justifyContent = "left"
div.style.margin='10px 0'
document.querySelector('.koa').appendChild(div)
},1000)
}
// https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp
return (
<div>
<div className='koa'></div>
<input ref={inp}></input>
<button onClick={() => {
ws.send(inp.current.value)
let div = document.createElement('DIV')
div.innerHTML = `
<p style="margin: 0px 10px;padding: 10px 30px;border: 1px solid blue;">${inp.current.value}</p>
<img style="width: 40px; height: 40px;" src='https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp' />
`
div.style.width = "80vw"
div.style.display = "flex"
div.style.alignItems = 'center'
div.style.justifyContent = "right"
div.style.margin='10px 0'
document.querySelector('.koa').appendChild(div)
inp.current.value = ''
}}>发送</button>
</div>
)
}
export default Index