Created
February 22, 2021 02:20
-
-
Save TylerLafayette/963d1d1ba27ff795cb9b59dc72b93014 to your computer and use it in GitHub Desktop.
TCP Chat Server in Go
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" | |
"math/rand" | |
"net" | |
"strings" | |
"time" | |
) | |
type Message struct { | |
Username string | |
Message string | |
} | |
func reader(c net.Conn, newConnections chan net.Conn, newMessages chan Message) { | |
fmt.Printf("New connection from %s¥n", c.RemoteAddr().String()) | |
c.Write([]byte("Please enter a username: ")) | |
data, err := bufio.NewReader(c).ReadString('¥n') | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
name := strings.TrimSpace(string(data)) | |
newConnections <- c | |
for { | |
data, err := bufio.NewReader(c).ReadString('¥n') | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
input := strings.TrimSpace(string(data)) | |
if input == "DISCONNECT" { | |
break | |
} | |
newMessages <- Message{ | |
Username: name, | |
Message: input, | |
} | |
} | |
c.Close() | |
} | |
func distributor(newConnections chan net.Conn, newMessages chan Message) { | |
connections := make(map[net.Conn]bool) | |
for { | |
select { | |
case conn := <-newConnections: | |
connections[conn] = true | |
case message := <-newMessages: | |
for conn := range connections { | |
num, err := conn.Write([]byte(fmt.Sprintf("%s: %s¥n", message.Username, message.Message))) | |
if num <= 0 || err != nil { | |
fmt.Println("Removing connection") | |
delete(connections, conn) | |
} | |
} | |
} | |
} | |
} | |
func main() { | |
server, err := net.Listen("tcp4", ":3214") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer server.Close() | |
rand.Seed(time.Now().Unix()) | |
newConnections := make(chan net.Conn) | |
newMessages := make(chan Message) | |
go distributor(newConnections, newMessages) | |
for { | |
conn, err := server.Accept() | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
go reader(conn, newConnections, newMessages) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment