基于go的websocket大多使用gorilla/websocket

iris也提供了websoket的封装,github.com/kataras/iris/v12/websocket

不过iris官方给的示例基本上都是依赖官方的js库实现的neffos.js

Neffos.js对websocket进行了封装,主要是房间进入和离开等事件的绑定,

对于消息的传递也使用了自己定义的格式,不同的字段使用分号进行分割

例如:;;;;0;0;helloworld,查看iris中源码看到Message的定义:


type Message struct {wait string
// The Namespace that this message sent to/received from.
Namespace string
// The Room that this message sent to/received from.
Room string
// The Event that this message sent to/received from.
Event string
// The actual body of the incoming/outcoming data.
Body []byte
// The Err contains any message's error, if any.
// Note that server-side and client-side connections can return an error instead of a message from each event callbacks,
// except the clients's force Disconnect which its local event doesn't matter when disconnected manually.
Err error
// if true then `Err` is filled by the error message and
// the last segment of incoming/outcoming serialized message is the error message instead of the body.
isError bool
isNoOp  bool
isInvalid bool
// the CONN ID, filled automatically if `Server#Broadcast` first parameter of sender connection's ID is not empty,
// not exposed to the subscribers (rest of the clients).
// This is the ID across neffos servers when scale.
from string
// When sent by the same connection of the current running server instance.
// This field is serialized/deserialized but it's clean on sending or receiving from a client
// and it's only used on StackExchange feature.
// It's serialized as the first parameter, instead of wait signal, if incoming starts with 0x.
FromExplicit string // the exact Conn's pointer in this server instance.
// Reports whether this message is coming from a stackexchange.
// This field is not exposed and it's not serialized at all, ~local-use only~.
//
// The "wait" field can determinate if this message is coming from a stackexchange using its second char,
// This value set based on "wait" on deserialization when coming from remote side.
// Only server-side can actually set it.
FromStackExchange bool
// To is the connection ID of the receiver, used only when `Server#Broadcast` is called, indeed when we only need to send a message to a single connection.
// The Namespace, Room are still respected at all.
//
// However, sending messages to a group of connections is done by the `Room` field for groups inside a namespace or just `Namespace` field as usual.
// This field is not filled on sending/receiving.
To string
// True when event came from local (i.e client if running client) on force disconnection,
// i.e OnNamespaceDisconnect and OnRoomLeave when closing a conn.
// This field is not filled on sending/receiving.
// Err does not matter and never sent to the other side.
IsForced bool
// True when asking the other side and fire the respond's event (which matches the sent for connect/disconnect/join/leave),
// i.e if a client (or server) onnection want to connect
// to a namespace or join to a room.
// Should be used rarely, state can be checked by `Conn#IsClient() bool`.
// This field is not filled on sending/receiving.
IsLocal bool
// True when user define it for writing, only its body is written as raw native websocket message, namespace, event and all other fields are empty.
// The receiver should accept it on the `OnNativeMessage` event.
// This field is not filled on sending/receiving.
IsNative bool
// Useful rarely internally on `Conn#Write` namespace and rooms checks, i.e `Conn#DisconnectAll` and `NSConn#RemoveAll`.
// If true then the writer's checks will not lock connectedNamespacesMutex or roomsMutex again. May be useful in the future, keep that solution.
locked bool
// if server or client should write using Binary message or if the incoming message was readen as binary.
SetBinary bool
}

注意到有个IsNative的控制参数,使用OnNativeMessage事件和IsNative字段就可以使用自己的格式通过websoket传递数据:

// True when user define it for writing, only its body is written as raw native websocket message, namespace, event and all other fields are empty.
// The receiver should accept it on the `OnNativeMessage` event.
// This field is not filled on sending/receiving.
IsNative bool
msg:=websocket.Message{Body:[]byte("helloworld"),IsNative:true,
}

接下来使用iris/websocket实现简单的聊天通信,go主要代码如下:

ws := websocket.New(websocket.DefaultGorillaUpgrader, websocket.Events{websocket.OnNativeMessage: func(nsConn *websocket.NSConn, msg websocket.Message) error {log.Printf("Server got: %s from [%s]", msg.Body, nsConn.Conn.ID())ping := string(msg.Body)pong := strings.Replace(ping,"?", "!", len(ping))
pong = strings.Replace(pong, "么","",len(pong))mg := websocket.Message{Body:[]byte(pong),
IsNative:true,
}
nsConn.Conn.Write(mg)
return nil
},
})

完整go代码:

package mainimport ("log""strings""github.com/kataras/iris/v12""github.com/kataras/iris/v12/websocket"
)func main() {ws := websocket.New(websocket.DefaultGorillaUpgrader, websocket.Events{websocket.OnNativeMessage: func(nsConn *websocket.NSConn, msg websocket.Message) error {log.Printf("Server got: %s from [%s]", msg.Body, nsConn.Conn.ID())ping := string(msg.Body)pong := strings.Replace(ping,"?", "!", len(ping))pong = strings.Replace(pong, "么","",len(pong))mg := websocket.Message{Body:[]byte(pong),IsNative:true,}nsConn.Conn.Write(mg)return nil},})ws.OnConnect = func(c *websocket.Conn) error {log.Printf("[%s] Connected to server!", c.ID())return nil}ws.OnDisconnect = func(c *websocket.Conn) {log.Printf("[%s] Disconnected from server", c.ID())}ws.OnUpgradeError = func(err error) {log.Printf("Upgrade Error: %v", err)}app := iris.New()app.HandleDir("/","./html")app.Get("/msg", websocket.Handler(ws))app.Run(iris.Addr(":8080"))
}

html 代码:

<html>
<head><title>Client Page</title>
</head>
<body style="padding:10px;">
<input type="text" id="messageTxt" />
<button type="button" id="sendBtn">Send</button>
<div id="messages" style="width: 375px;margin:10 0 0 0px;border-top: 1px solid black;">
</div>
<script type="text/javascript">var HOST = "localhost:8080"var messageTxt = document.getElementById("messageTxt");var messages = document.getElementById("messages");var sendBtn = document.getElementById("sendBtn")w = new WebSocket("ws://" + HOST + "/msg");w.onopen = function () {console.log("Websocket connection enstablished");};w.onclose = function () {appendMessage("<div><center><h3>Disconnected</h3></center></div>");};w.onmessage = function (message) {appendMessage("<div> srv: " + message.data + "</div>");};sendBtn.onclick = function () {myText = messageTxt.value;messageTxt.value = "";appendMessage("<div style='color: red'> me: " + myText + "</div>");w.send(myText);};messageTxt.addEventListener("keyup", function (e) {if (e.keyCode === 13) {e.preventDefault();sendBtn.click();}});function appendMessage(messageDivHTML) {messages.insertAdjacentHTML('afterbegin', messageDivHTML);}
</script>
</body>
</html>

效果:

go-iris-websocket 简单聊天通信相关推荐

  1. LINUX下UDP实现消息镜像通信,linux环境下基于udp socket简单聊天通信

    客户端代码:client.c /* * File: main.c * Author: guanyy * * Created on 20161202 * * 主要实现:客户端和服务端相互通信 */ #i ...

  2. SpringBoot +WebSocket实现简单聊天室功能实例

    SpringBoot +WebSocket实现简单聊天室功能实例) 一.代码来源 二.依赖下载 三.数据库准备(sql) 数据库建表并插入sql 四.resources文件配置 application ...

  3. WebSocket 实现简单聊天功能

    利用WebSocket长连接实现即使通讯,可以实现个人单独聊天,内容不需要存服务器,这里只有前端代码,后端负责传递消息和用户列表. <template><div><div ...

  4. WebSocket实现简单聊天功能案例

    简介 1.使用WebSocket实现的一个简单的聊天功能业务 2.使用了SpringBoot的ApplicationEvent事件监听用来与业务解耦 3.需要注意的是websocket的长连接默认会在 ...

  5. 利用socket.io+nodejs打造简单聊天室

    代码地址如下: http://www.demodashi.com/demo/11579.html 界面展示: 首先展示demo的结果界面,只是简单消息的发送和接收,包括发送文字和发送图片. ws说明: ...

  6. 基于django channel 实现websocket的聊天室

    websocket ​ 网易聊天室? ​ web微信? ​ 直播? 假如你工作以后,你的老板让你来开发一个内部的微信程序,你需要怎么办?我们先来分析一下里面的技术难点 消息的实时性? 实现群聊 现在有 ...

  7. websocket以及聊天室的实现

    HTTP keep-alive参考博文 socketio跨域 socketio跨域问题自己去了解 WebSocket websocket可以实现客户端与服务端之间的数据实时通信.(长连接) 网络通信过 ...

  8. SSM(五)基于webSocket的聊天室

    SSM(五)基于webSocket的聊天室 前言 不知大家在平时的需求中有没有遇到需要实时处理信息的情况,如站内信,订阅,聊天之类的.在这之前我们通常想到的方法一般都是采用轮训的方式每隔一定的时间向服 ...

  9. node.js入门 - 2.创建一个简单聊天室

    这篇文章将通过开发一个简单聊天室的方式,介绍node.js的net模块. 一.第一版,只向客户端发送信息   我们先实现一个简单的版本,代码如下: var net=require('net'); va ...

最新文章

  1. 数据探索很麻烦?推荐一款强大的特征分析可视化工具:yellowbrick
  2. winsock I/O模型
  3. SEO优化可以从这几个方面着手
  4. 暗通道优先的图像去雾算法(上)
  5. shell基础:多命令顺序执行与管道符
  6. 阴差阳错2019-12-13
  7. 疫情期间用掉了1400亿个!二维码会被人类扫完吗?
  8. 【转】Service深入分析
  9. sql 百分号_SQL思维导图和代码分享
  10. JQuery中如何动态修改input的type属性
  11. php 替换alt,PHP 实现自动添加或者替换 内容的IMG标签的 alt title 属性
  12. ios8.1.3 刷机8.2beta越狱 真机调试 一起喝成
  13. 百度云图片识别(ImageRecognition)
  14. 视频转GIF动图MATLAB源码
  15. 验证码错误的可能问题
  16. 尾气冒黑烟是什么问题_当你的汽车排气管冒黑烟时,该如何处理呢?
  17. MC9S12XS128nbsp;16位PWMnbsp;电…
  18. 笔记:基本的世代交叠模型
  19. pbl和sbl_ROKSO、SBL、XBL、PBL、DBL 是什么意思?
  20. 终于有人把股市集合竞价的秘密说清楚了

热门文章

  1. 一文掌握jieba分词器的常见用法,附带案例
  2. 2023最新通信工程毕业设计题目选题推荐100例
  3. 深度学习-瓶颈结构(Bottleneck)
  4. bottleneck与basicblock
  5. 李斌、李想、何小鹏的性格与宿命
  6. VScode打开vivado中v文件
  7. Zookeeper简介及核心概念
  8. Action 中获取表单数据的三种方式
  9. 2022CSP-J2题解
  10. 2021年有哪些新机会?我们在杭州现场告诉你! | 玲听2021跨年演讲