Exemplo n.º 1
0
func main() {
	port := 8080
	s := socketio.SocketIOHandler()

	r := Room{}
	r.sessions = make(map[*socketio.Session]string)

	s.On("nickname", "", func(s *socketio.Session, m *socketio.Message) (interface{}, error) {
		nickname := (m.JsonData.([]interface{})[0]).(string)
		r.Join(nickname, s)
		r.Broadcast("nicknames", listNick(&r))
		r.Broadcast("announcement", fmt.Sprintf("%s has connected", nickname))

		if m.Ack {
			reply := socketio.Message{Type: socketio.ACK, Endpoint: m.Endpoint, SubId: m.Id}
			return &reply, nil
		}
		return nil, nil
	})

	s.On("user message", "", func(s *socketio.Session, m *socketio.Message) (interface{}, error) {
		nickname := r.sessions[s]
		r.Emit("msg_to_room", nickname, nickname, (m.JsonData.([]interface{})[0]).(string))
		return nil, nil
	})

	fmt.Println("Starting server on port ", port)
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/static/", staticHandler)
	http.HandleFunc("/tests/", staticHandler)
	http.Handle("/socket.io/", s)
	http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
Exemplo n.º 2
0
func main() {
	port := 8080
	s := socketio.SocketIOHandler()
	s.Settings.HeartbeatTimeout = 2
	s.Settings.ClosingTimeout = 2
	s.On("requestack", "/test", func(s *socketio.Session, m *socketio.Message) (interface{}, error) {
		s.Logf("Request ack")
		res := make([]interface{}, 2)
		res[0] = 1
		res[1] = "ack"
		if m.Ack {
			data, _ := json.Marshal(res)
			reply := socketio.Message{Type: socketio.ACK, Endpoint: m.Endpoint, Data: data, SubId: m.Id}
			s.Logf("Posting ACK reply: %s", reply)
			return &reply, nil
		}
		return res, nil
	})

	s.On("noop", "/test", func(s *socketio.Session, m *socketio.Message) (interface{}, error) {
		return nil, nil
	})

	s.On("connect", "/logs", func(s *socketio.Session, m *socketio.Message) (interface{}, error) {
		return nil, nil
	})

	s.On("connect", "/error", func(s *socketio.Session, m *socketio.Message) (interface{}, error) {
		return nil, errors.New("Connection refused")
	})
	fmt.Println("Starting server on port ", port)
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/static/", staticHandler)
	http.HandleFunc("/tests/", staticHandler)
	http.Handle("/socket.io/", s)
	http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}