Exemple #1
0
func (server *Server) join(conn net.Conn) {
	server.currentClientId = server.currentClientId + 1
	client := InitClient(conn, server.currentClientId)
	server.clients[client.id] = client

	msg := SystemMessage(fmt.Sprintf("「%v」加入聊天:「%v」", client.name, conn.RemoteAddr().String()))
	server.broadcast(msg)
	utils.Log().Debug(msg.Stringer())

	// Message
	go func() {
		for {
			msg := <-client.incoming

			server.incoming <- msg
		}
	}()

	// Quit
	go func() {
		for {
			c := <-client.quiting
			server.quiting <- c
		}
	}()
}
Exemple #2
0
func (client *Client) write() {
	for data := range client.outgoing {
		if _, err := client.writer.WriteString(data.Stringer()); err != nil {
			utils.Log().Error("为「%v」发送消息失败1: %v", client.name, err)
			client.quit()
			return
		}

		if err := client.writer.Flush(); err != nil {
			utils.Log().Error("为「%v」发送消息失败2: %v", client.name, err)
			client.quit()
			return
		}
	}

}
Exemple #3
0
func (server *Server) Start() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		utils.Log().Error("服务器启动失败: %v", err)
		os.Exit(-1)
	}
	server.listener = listener

	utils.Log().Notice("服务器已经启动, 正在监听8080端口")
	for {
		if conn, err := listener.Accept(); err != nil {
			utils.Log().Error("接收信息失败: %v", err)
		} else {
			server.connecting <- conn
		}

	}
}
Exemple #4
0
func (server *Server) quit(client *Client) {
	if _, ok := server.clients[client.id]; ok && client.conn != nil {
		msg := SystemMessage(fmt.Sprintf("「%v」退出聊天:「%v」", client.name, client.conn.RemoteAddr().String()))
		client.close()
		delete(server.clients, client.id)

		utils.Log().Debug(msg.Stringer())
		server.broadcast(msg)

	}

}
Exemple #5
0
func (client *Client) read() {
	for {
		if line, _, err := client.reader.ReadLine(); err == nil {
			input := strings.TrimSpace(string(line))
			if input != "" {
				msg := Message{
					client:      client,
					messageType: MESSAGE_TYPE_PLAYER,
					message:     string(line),
					sentAt:      time.Now().UTC().Unix(),
				}

				client.incoming <- msg
			}

		} else {
			utils.Log().Error("接收「%v」的消息失败: %v", client.name, err)
			client.quit()
			return

		}
	}
}
Exemple #6
0
func (server *Server) broadcast(msg Message) {
	utils.Log().Debug(msg.Stringer())
	for _, client := range server.clients {
		client.outgoing <- msg
	}
}