Created
March 21, 2016 23:56
-
-
Save jingkaihe/30423866a162be3c1a06 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"net" | |
) | |
type msgs chan string | |
type client struct { | |
name string | |
msgbox msgs | |
} | |
var ( | |
messages = make(chan string) | |
entering = make(chan client) | |
leaving = make(chan client) | |
) | |
func boradcast() { | |
clients := make(map[client]bool) | |
for { | |
select { | |
case msg := <-messages: | |
for cli := range clients { | |
cli.msgbox <- msg | |
} | |
case cli := <-leaving: | |
delete(clients, cli) | |
close(cli.msgbox) | |
case cli := <-entering: | |
clients[cli] = true | |
} | |
} | |
} | |
func writing(conn net.Conn, cli client) { | |
for msg := range cli.msgbox { | |
fmt.Fprintln(conn, msg) | |
} | |
} | |
func handleConnect(conn net.Conn) { | |
cli := client{ | |
name: conn.RemoteAddr().String(), | |
msgbox: make(msgs), | |
} | |
go writing(conn, cli) | |
entering <- cli | |
messages <- cli.name + " has joined the chat" | |
scanner := bufio.NewScanner(conn) | |
for scanner.Scan() { | |
messages <- cli.name + ": " + scanner.Text() | |
} | |
leaving <- cli | |
messages <- cli.name + " left the chat" | |
conn.Close() | |
} | |
func main() { | |
ln, _ := net.Listen("tcp", ":8080") | |
go boradcast() | |
for { | |
conn, _ := ln.Accept() | |
go handleConnect(conn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment