Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "fmt"
- "log"
- "net"
- )
- type (
- ServerRoom struct {
- clientIdIterator int
- messages chan string
- clients map[*Client]bool
- newConnections chan *Client
- deadConnections chan *Client
- }
- Client struct {
- id int
- conn net.Conn
- reader *bufio.Reader
- writer *bufio.Writer
- }
- )
- func main() {
- listener, err := net.Listen("tcp", ":1337")
- if err != nil {
- fmt.Println("Some error occured:", err.Error())
- }
- defer listener.Close()
- room := &ServerRoom{
- 0,
- make(chan string),
- make(map[*Client]bool),
- make(chan *Client),
- make(chan *Client),
- }
- go func() {
- for {
- conn, err := listener.Accept()
- if err != nil {
- fmt.Println("Some error occured:", err.Error())
- }
- reader := bufio.NewReader(conn)
- writer := bufio.NewWriter(conn)
- client := &Client{
- id: room.clientIdIterator,
- conn: conn,
- reader: reader,
- writer: writer,
- }
- room.clients[client] = false
- room.clientIdIterator++
- room.newConnections <- client
- }
- }()
- for {
- select {
- case client := <-room.newConnections:
- log.Printf("Accepted new client, #%d", client.id)
- go func() {
- for {
- incoming, err := client.reader.ReadString('\n')
- if err != nil {
- break
- }
- room.messages <- fmt.Sprintf("Client %d > %s", client.id, incoming)
- }
- }()
- case message := <-room.messages:
- for client := range room.clients {
- go func() {
- _, err := client.writer.WriteString(message)
- if err != nil {
- room.deadConnections <- client
- }
- err = client.writer.Flush()
- if err != nil {
- room.deadConnections <- client
- }
- }()
- }
- case client := <-room.deadConnections:
- log.Printf("Client %d disconnected", client.id)
- delete(room.clients, client)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement