hullqin / go-websocket-examples Goto Github PK
View Code? Open in Web Editor NEWSome Go WebSocket examples based on gorilla/websocket. Including echo server, chat room, etc.
License: BSD 2-Clause "Simplified" License
Some Go WebSocket examples based on gorilla/websocket. Including echo server, chat room, etc.
License: BSD 2-Clause "Simplified" License
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Identity of room.
roomId string
// Registered clients.
clients map[*Client]bool
// Inbound messages from the clients.
broadcast chan []byte
// Unregister requests from clients.
unregister chan *Client
}
func newHub(roomId string) *Hub {
return &Hub{
roomId: roomId,
broadcast: make(chan []byte),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
}
}
func (h *Hub) run() {
defer func() {
close(h.unregister)
close(h.broadcast)
}()
for {
select {
case client := <-h.unregister:
roomMutex := roomMutexes[h.roomId]
roomMutex.Lock()
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
if len(h.clients) == 0 {
house.Delete(h.roomId)
roomMutex.Unlock()
mutexForRoomMutexes.Lock()
if roomMutex.TryLock() {
if len(h.clients) == 0 {
delete(roomMutexes, h.roomId)
}
roomMutex.Unlock()
}
mutexForRoomMutexes.Unlock()
return
}
}
roomMutex.Unlock()
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}
case message := <-h.broadcast: 语句后面应该也要枷锁吧,不然连接进来的时候,跟这个有冲突
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.