You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
1.8 KiB
Go

3 years ago
/**
* @Author: jager
* @Email: lhj168os@gmail.com
* @File: main
* @Date: 2021/10/18 11:15
* @package: wechat
* @Version: v1.0.0
*
* @Description:
*
*/
package main
import (
3 years ago
"fmt"
3 years ago
"github.com/jageros/hawox/contextx"
"github.com/jageros/hawox/wsc"
3 years ago
"log"
3 years ago
"net/http"
3 years ago
"unicode"
3 years ago
"wechat/types"
3 years ago
"wechat/view"
3 years ago
)
func main() {
3 years ago
ctx, cancel := contextx.Default()
defer cancel()
3 years ago
var err error
3 years ago
3 years ago
var sess *wsc.Session
3 years ago
m := wsc.New(ctx)
3 years ago
view.OnMessage("请发送本人手机号码加入聊天室!\n")
3 years ago
view.OnSendMsg(func(msg string) {
3 years ago
if sess == nil {
if len(msg) != 11 {
view.OnMessage("手机号码格式错误!\n")
return
}
for _, r := range msg {
if !unicode.Is(unicode.Number, r) {
view.OnMessage("手机号码格式错误!\n")
return
}
}
uid := msg
h := http.Header{}
h.Add("uid", uid)
sess, err = m.ConnectWithHeader("ws://wechat.hawtech.cn/ws/wechat/1", h, map[string]interface{}{"uid": uid})
if err != nil {
view.OnMessage(fmt.Sprintf("创建websocket链接错误手机号码:%s 错误信息:%v\n", uid, err))
return
}
view.OnMessage("登录成功!\n")
return
}
data := &types.Msg{
MsgID: 1,
Msg: msg,
}
bytes, err := types.Marshal(data)
3 years ago
if err != nil {
3 years ago
view.OnMessage(fmt.Sprintf("编码错误: %v", err))
return
}
err = sess.WriteBinary(bytes)
if err != nil {
3 years ago
}
})
m.HandleMessageBinary(func(session *wsc.Session, bytes []byte) {
3 years ago
msg, err := types.Unmarshal(bytes)
3 years ago
if err != nil {
3 years ago
view.OnMessage(fmt.Sprintf("解码错误:%v", err))
3 years ago
return
}
switch msg.MsgID {
case 1:
view.OnMessage(msg.Msg)
3 years ago
3 years ago
case 2:
view.UpdateOnline(msg.Msg)
3 years ago
3 years ago
default:
log.Printf("MsgId=%d Msg=%s", msg.MsgID, msg.Msg)
}
})
3 years ago
3 years ago
err = view.Run()
3 years ago
if err != nil {
3 years ago
log.Fatal(err)
3 years ago
}
}