Last active
October 7, 2017 17:23
-
-
Save donovank/78001644ac5a0b805cbdc99619f3bd43 to your computer and use it in GitHub Desktop.
Minimalistic one-way TCP chat in Golang
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 ( | |
"fmt" | |
"log" | |
"net" | |
) | |
var send = make(chan string) | |
var id = 1 | |
type Session struct { | |
MaxClients int | |
Clients int | |
Users []User | |
} | |
type User struct { | |
Nickname int | |
IP string | |
Conn net.Conn | |
} | |
func (u *User) Listen() { | |
for { | |
b := make([]byte, 1024) | |
u.Conn.Read(b) | |
send <- fmt.Sprintf("%d", u.Nickname) + ": " + string(b[:]) | |
} | |
} | |
func CreateUser(conn net.Conn) User { | |
usr := User{id, conn.RemoteAddr().String(), conn} | |
id++ | |
go usr.Listen() | |
return usr | |
} | |
func checkerr(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} | |
func main() { | |
c := 10 | |
session := Session{c, 0, make([]User, 0)} | |
listener, err := net.Listen("tcp", ":4444") | |
checkerr(err) | |
go func() { | |
for { | |
conn, err := listener.Accept() | |
checkerr(err) | |
if session.Clients >= session.MaxClients { | |
conn.Write([]byte("Participant limit reached.\n")) | |
conn.Close() | |
break | |
} else { | |
log.Printf("User %s joined.\n", conn.RemoteAddr().String()) | |
} | |
session.Users = append(session.Users, CreateUser(conn)) | |
} | |
}() | |
var msg string | |
for { | |
msg = <-send | |
for _, u := range session.Users { | |
u.Conn.Write([]byte(msg)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment