go-chat/process/process.go

81 lines
1.2 KiB
Go
Raw Permalink Normal View History

2021-04-22 06:12:35 +00:00
package process
import (
"chat/message"
"encoding/json"
"fmt"
2021-05-07 10:08:46 +00:00
"io"
2021-04-22 06:12:35 +00:00
"net"
"reflect"
)
type Ms struct {
Msg message.Message
Conn net.Conn
}
type Transfer struct {
Conn net.Conn
Buf [64 << 10]byte
}
func WriteConn(c net.Conn, message message.Message) error {
m, _ := json.Marshal(message)
_, err := c.Write(m)
if err != nil {
return err
}
return nil
}
func (t *Transfer) ReadConn(c chan Ms) {
defer func() {
err := t.Conn.Close()
if err != nil {
fmt.Println(err)
return
}
}()
for {
var info = t.Buf
i, err := t.Conn.Read(info[:])
if err != nil {
2021-05-07 10:08:46 +00:00
if err == io.EOF {
fmt.Println("连接已断开。。。。")
} else {
fmt.Println(err, "errrrrrrrrrrrrr")
}
2021-04-22 06:12:35 +00:00
return
}
msg := message.Message{}
err = json.Unmarshal(info[:i], &msg)
if err != nil {
fmt.Println(err)
}
2021-04-25 01:53:49 +00:00
tt, ok := message.MsgType[msg.Type]
var mm = msg
if ok {
mm.Data = reflect.New(tt).Interface()
err = json.Unmarshal(info[:i], &mm)
if err != nil {
fmt.Println(err)
}
2021-04-22 06:12:35 +00:00
}
w := Ms{
Msg: mm,
Conn: t.Conn,
}
c <- w
}
}
func Read(conn net.Conn, c chan Ms) {
t := Transfer{
Conn: conn,
Buf: [65536]byte{},
}
t.ReadConn(c)
}