WebSocket是一种长连接的双向通信方式,一旦连接完成,双方就能相互主动发起通信,每次通信不需要再次连接。

客户端向服务器发送握手报文,服务器响应确认握手的报文,连接就建立了,连接完成后,双方都可以主动发送数据,直到有一方发来断开连接的信号来关闭连接。
下面使用了一个WebSocket在线测试的url,客户端发送了什么消息,服务端就会返回什么消息,用id来区分客户端和服务端。
`import { webSocket } from '@kit.NetworkKit'
import { promptAction } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit'
interface messageInfo {
//用户id,我这里的设置:客户端的id为1001,服务端id为1002
id: string
msg: string
}
@Entry
@Component
struct WebSocketPage {
@State data: messageInfo[] = [] //消息数组
@State myMsg: string = ''
//这是websocket在线测试url,客户端发送什么,服务器就会返回什么
@State url: string = 'ws://124.222.224.186:8800/websocket'
ws: webSocket.WebSocket | null = null
async aboutToAppear() {
this.connect2Server(this.url)
this.receiveMsg()
}
//连接服务端
connect2Server(defaultIpAddress: string) {
this.ws = webSocket.createWebSocket();
//根据URL地址,建立

最低0.47元/天 解锁文章

9657

被折叠的 条评论
为什么被折叠?



