当前位置:   article > 正文

【鸿蒙实战开发】WebSocket连接_鸿蒙websocket长连接

鸿蒙websocket长连接

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

客户端向服务器发送握手报文,服务器响应确认握手的报文,连接就建立了,连接完成后,双方都可以主动发送数据,直到有一方发来断开连接的信号来关闭连接。

下面使用了一个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地址,建立一个WebSocket连接
 this.ws.connect(defaultIpAddress, (err: BusinessError, value: boolean) => {
 if (!err) {
 //连接成功
 promptAction.showToast({ message: 'connect success ' })
 } else {
 AlertDialog.show({ message: 'connect fail ' + err.message })
 }
 })

 this.ws.on('open', (err: BusinessError, value: object) => {
 //打开webSocket失败
 if (err) {
 AlertDialog.show({ message: JSON.stringify(err) })
 }
 })
 }

 //接收到服务器消息
 receiveMsg() {
 if (this.ws) {
 this.ws.on('message', (err, value) => {
 this.data.push({ id: '1002', msg: JSON.stringify(value) })
 })
 }
 }

 //发送消息到服务端
 sendMsg2Server(msg: string) {
 if (this.ws) {
 this.ws.send(msg)
 .catch((e: Error) => {
 AlertDialog.show({ message: '发送失败' + e.message })
 })
 }
 }

 build() {
 Navigation() {
 Column() {
 List() {
 ForEach(this.data, (Item: messageInfo) => {
 ListItem() {
 Row() {
 //网络图片需要打开网络权限
 Image(Item.id === '1001' ?
 "https://tse3-mm.cn.bing.net/th/id/OIP-C.JRIYJ3EqtcLF1LwK3oxjgAHaGg?w=201&h=181&c=7&r=0&o=5&dpr=1.3&pid=1.7" :
 "https://tse3-mm.cn.bing.net/th/id/OIP-C.7Z068v6GRuOJVYYUSHsBDgHaNK?w=115&h=182&c=7&r=0&o=5&dpr=1.3&pid=1.7")
 .height(40)
 .width(40)
 .borderRadius(6)
 Row() {
 Text(Item.msg)
 .backgroundColor(Item.id === '1001' ? Color.Orange : Color.Yellow)
 .padding(10)
 .lineHeight(24)
 .margin({
 left: 10,
 right: 10
 })
 .borderRadius(5)
 }
 .layoutWeight(6)
 .justifyContent(Item.id === '1001' ? FlexAlign.End : FlexAlign.Start)

 Text().layoutWeight(1)
 }
 .alignItems(VerticalAlign.Top)
 .direction(Item.id === '1001' ? Direction.Rtl : Direction.Ltr)
 }
 .margin({ bottom: 10 })
 })
 }
 .padding(10)
 .backgroundColor(Color.Pink)
 .layoutWeight(1)

 TextInput({ placeholder: '请输入', text: $this.myMsg })
 .onSubmit(() => {
 this.sendMsg2Server(this.myMsg)
 this.data.push({ id: '1001', msg: this.myMsg } as messageInfo)
 //清空输入框内容
 this.myMsg = ''
 })
 }
 .height('100%')
 .width('100%')
 }
 .title('webSocket通信')
 .titleMode(NavigationTitleMode.Mini)
 }
}` </pre>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119

写在最后

●如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
●点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
●关注小编,同时可以期待后续文章ing

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/963981
推荐阅读
相关标签