一对一聊天
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一对一聊天相关的知识,希望对你有一定的参考价值。
package main
import (
"github.com/gorilla/websocket"
"net/http"
"log"
)
var (
PushMessage = make(chan message, 100)
Clients = make(map[string] *websocket.Conn)
)
var (
// http升级websocket协议的配置
upgrader = websocket.Upgrader{
// 允许所有CORS跨域请求
CheckOrigin: func(r *http.Request) bool {
return true
},
}
)
//消息结构
type message struct {
From string //发送人id
To string //接收人id
Sess string //session的id
Msg string //消息内容
}
func wsHandler(writer http.ResponseWriter, request *http.Request) {
var (
ws *websocket.Conn
err error
)
//完成握手应答
if ws, err = upgrader.Upgrade(writer, request, nil); err != nil {
return
}
//收数据
for {
var msg message
err = ws.ReadJSON(&msg)
//log.Printf("From: %v", msg.From)
if err != nil {
//log.Printf("error1: %v", err)
//delete(Clients, msg.From)
return
}
Clients[msg.From] = ws
PushMessage <- msg
}
defer ws.Close()
}
func toMessage() {
for {
msg := <-PushMessage
if _, ok := Clients[msg.To]; ok {
err := Clients[msg.To].WriteJSON(msg.Msg)
if err != nil {
log.Printf("err2:%v", err)
}
}
}
}
func main() {
http.HandleFunc("/ws", wsHandler)
log.Println("server :9988")
go toMessage()
err := http.ListenAndServe(":9988", nil)
if err != nil {
panic(err)
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket测试程序 </title>
<script>
window.addEventListener("load", function (evt) {
var output = document.getElementById("output");
var input = document.getElementById("input")
var ws;
var print = function (message) {
var d = document.createElement("div");
d.innerHTML = message;
output.appendChild(d);
};
document.getElementById("open").onclick = function (ev) {
if (ws) {
return false;
}
ws = new WebSocket("ws://127.0.0.1:9988/ws");
ws.onopen = function (ev) {
print("连接成功");
};
ws.onclose = function (ev) {
print("连接关闭");
};
ws.onerror = function (ev) {
print("发生错误 " + ev.data)
};
ws.onmessage = function (ev1) {
print("服务端消息: " + ev1.data)
};
return false
};
document.getElementById("send").onclick = function (ev) {
if (!ws) {
return false
}
if (input.value !== "") {
ws.send(input.value)
} else {
print("发送内容不能为空")
}
};
document.getElementById("close").onclick = function (ev) {
if (ws) {
ws.close()
}
}
})
</script>
</head>
<body>
<div>
<br>
websocket测试程序,消息又客户端发送到server然后原封不动的返回,server使用go实现
<br>
<br>
<br>
<input type="button" value="连接" id="open">
<input placeholder="输入要发送的消息..." id="input">
<input type="button" value="发送" id="send">
<input type="button" value="关闭" id="close">
</div>
<div id="output">
</div>
</body>
</html>
打开两个页面:
一个发送:{"From":"666","To":"888","Sess":"sess_666","msg":"hello 666"}
一个发送:{"From":"888","To":"666","Sess":"sess_888","msg":"hello 888"}
以上是关于一对一聊天的主要内容,如果未能解决你的问题,请参考以下文章
基于flask框架,使用websocket实现一对一聊天室功能
第98题JAVA高级技术-网络编程17(简易聊天室12:实现客户端一对一聊天)