一、搭建websocket
搭建node项目并安装依赖:
npm install express -g
npm install express-generator -g
express myproject
npm install ws
在 app.js 中配置 ws:
var websocket = require('ws');
var server = new websocket.Server({
port: 1234
});
server.on('open', () => {
console.log('open');
});
server.on('close', () => {
console.log('close');
});
server.on('connection', (ws, req) => {
console.log('connection连接成功');
ws.on('message', (data) => {
server.clients.forEach((item) => {
if (item.readyState === ws.OPEN) {
item.send('' + data);
}
});
});
});
客户端连接: A 页面通过iframe内嵌B页面测试通信 A页面:
import React, { useEffect, useRef, useState } from 'react';
import './index.scss';
export default function learn2() {
useEffect(() => {
const ws = new WebSocket('ws://localhost:1234');
ws.onopen = () => {
console.log('连接成功');
setws(ws);
};
ws.onerror = (err) => {
console.log('连接失败:', err);
};
ws.onclose = (close: any) => {
console.log('连接关闭:', close);
};
ws.onmessage = (event) => {
console.log('通信: ', event);
const info = JSON.parse(event?.data);
setwsData((pre: any) => {
return [...pre, info];
});
};
}, []);
const myref = useRef<any>(null);
const [ws, setws] = useState<any>(null);
const [wsData, setwsData] = useState<any>([]);
const sendMsg = (key: number) => {
if (key == 13) {
const msg = myref.current.value;
const msgToJson = JSON.stringify({ msg, id: 'me' });
ws.send(msgToJson);
myref.current.value = '';
}
};
return (
<div className="learn2">
<div className="content">
<div>
<div>
<input
type="text"
ref={myref}
onKeyDown={(event) => {
sendMsg(event.keyCode);
}}
/>
<button onClick={() => sendMsg(13)}>发送</button>
</div>
{}
<div className="talkWrap">
{wsData.map((item: any, idx: any) => {
if (item.id == 'me') {
return (
<p key={idx} style={{ textAlign: 'right' }}>
{item.id}:{item.msg}
</p>
);
}
return (
<p key={idx}>
{item.id}:{item.msg}
</p>
);
})}
</div>
</div>
<iframe src="http://localhost:3000/learn3" width={800} height={800} />
</div>
</div>
);
}
B:
import { send } from 'process';
import React, { useEffect, useRef, useState } from 'react';
import './index.scss';
export default function learn3() {
useEffect(() => {
const ws = new WebSocket('ws://localhost:1234');
ws.onopen = () => {
console.log('连接成功');
setws(ws);
};
ws.onerror = (err) => {
console.log('连接失败:', err);
};
ws.onclose = (close: any) => {
console.log('连接关闭:', close);
};
ws.onmessage = (event) => {
console.log('通信3: ', event);
const info = JSON.parse(event?.data);
setwsData((pre: any) => {
return [...pre, info];
});
};
}, []);
const myref = useRef<any>(null);
const [ws, setws] = useState<any>(null);
const [wsData, setwsData] = useState<any>([]);
const sendMsg = (key: number) => {
if (key == 13) {
const msg = myref.current.value;
const msgToJson = JSON.stringify({ msg, id: 'he' });
ws.send(msgToJson);
myref.current.value = '';
}
};
return (
<div className="learn3">
<div>
<input
type="text"
ref={myref}
onKeyDown={(event) => {
sendMsg(event.keyCode);
}}
/>
<button onClick={() => sendMsg(13)}>发送</button>
</div>
{}
<div className="talkWrap">
{wsData.map((item: any, idx: any) => {
if (item.id == 'he') {
return (
<p key={idx} style={{ textAlign: 'right' }}>
{item.id}:{item.msg}
</p>
);
}
return (
<p key={idx}>
{' '}
{item.id}:{item.msg}
</p>
);
})}
</div>
</div>
);
}
|