Example #1
0
func handleWebSocket(ws *websocket.Conn) {
	for {
		opcode, reader, err := ws.NextReader()
		if err != nil {
			break
		}

		switch opcode {
		case websocket.OpText:
			msg, err1 := ioutil.ReadAll(reader)
			if err1 != nil {
				break
			}

			writer, err2 := ws.NextWriter(websocket.OpText)
			if err2 != nil {
				break
			}

			writer.Write([]byte("你说: {"))
			writer.Write(msg)
			writer.Write([]byte("}"))
			writer.Close()
		}
	}

}
Example #2
0
func handleChat(ws *websocket.Conn) {

	poster := func() int {
		for {
			since := board.QHead
			recv_msg, next := board.GetMessages(since)
			since = next

			for _, m := range recv_msg {
				timems := m.Time.Unix()*1000 +
					int64(m.Time.Nanosecond()/1000000)

				timeStr := fmt.Sprintf("%016x", timems)
				send_msg := timeStr + m.Text
				ws.WriteMessage(websocket.OpText, []byte(send_msg))
			}
		}

		return 0
	}

	fetcher := func() int {
		for {
			opcode, reader, err := ws.NextReader()
			if err != nil {
				break
			}

			switch opcode {
			case websocket.OpText:
				{
					msg, err := ioutil.ReadAll(reader)
					if err != nil {
						break
					}

					board.PostMessage(string(msg))
				}
			case websocket.OpBinary:
				{
					msg, err := ioutil.ReadAll(reader)
					if err != nil {
						break
					}

					msgStr := fmt.Sprintf("%v", msg)
					board.PostMessage(string(msgStr))
				}
			}
		}

		return 0
	}

	sync_end := make(chan int)

	go func() { sync_end <- poster() }()
	fetcher()

	<-sync_end
}