| 30 | } |
| 31 | |
| 32 | func process(conn net.Conn) { |
| 33 | defer conn.Close() |
| 34 | |
| 35 | var buf [256]byte |
| 36 | for { |
| 37 | n, err := conn.Read(buf[:]) |
| 38 | if n == 0 { |
| 39 | if err == io.EOF { |
| 40 | break |
| 41 | } |
| 42 | fmt.Printf("Read message failed: %v\n", err) |
| 43 | continue |
| 44 | } |
| 45 | |
| 46 | var event = controller.MessageSendEvent{} |
| 47 | _ = json.Unmarshal(buf[:n], &event) |
| 48 | fmt.Printf("Receive Message:%+v\n", event) |
| 49 | |
| 50 | fromChatKey := fmt.Sprintf("%d_%d", event.UserId, event.ToUserId) |
| 51 | if len(event.MsgContent) == 0 { |
| 52 | chatConnMap.Store(fromChatKey, conn) |
| 53 | continue |
| 54 | } |
| 55 | |
| 56 | toChatKey := fmt.Sprintf("%d_%d", event.ToUserId, event.UserId) |
| 57 | writeConn, exist := chatConnMap.Load(toChatKey) |
| 58 | if !exist { |
| 59 | fmt.Printf("User %d offline\n", event.ToUserId) |
| 60 | continue |
| 61 | } |
| 62 | |
| 63 | pushEvent := controller.MessagePushEvent{ |
| 64 | FromUserId: event.UserId, |
| 65 | MsgContent: event.MsgContent, |
| 66 | } |
| 67 | pushData, _ := json.Marshal(pushEvent) |
| 68 | _, err = writeConn.(net.Conn).Write(pushData) |
| 69 | if err != nil { |
| 70 | fmt.Printf("Push message failed: %v\n", err) |
| 71 | } |
| 72 | } |
| 73 | } |