import ( "fmt" "net" ) func main() { // Listen on TCP port 8080 listener, err := net.Listen("tcp", ":8080") if err != nil { fmt.Println("Error listening:", err.Error()) return } defer listener.Close() fmt.Println("Listening on 0.0.0.0:8080") for { // Wait for a connection conn, err := listener.Accept() if err != nil { fmt.Println("Error accepting connection:", err.Error()) continue } // Handle the connection go func(conn net.Conn) { buf := make([]byte, 1024) _, err := conn.Read(buf) if err != nil { fmt.Println("Error reading:", err.Error()) conn.Close() return } // Echo back the message _, err = conn.Write(buf) if err != nil { fmt.Println("Error writing:", err.Error()) conn.Close() return } conn.Close() }(conn) } }
import ( "bufio" "fmt" "net" "sync" ) type Client struct { username string conn net.Conn } func main() { // Listen on TCP port 8080 listener, err := net.Listen("tcp", ":8080") if err != nil { fmt.Println("Error listening:", err.Error()) return } defer listener.Close() fmt.Println("Listening on 0.0.0.0:8080") clients := make([]*Client, 0) var mutex sync.Mutex for { // Wait for a connection conn, err := listener.Accept() if err != nil { fmt.Println("Error accepting connection:", err.Error()) continue } // Add the client to the client list mutex.Lock() clients = append(clients, &Client{conn: conn}) mutex.Unlock() // Prompt the client for a username go func(c *Client) { defer func() { // Remove the client from the client list when they disconnect mutex.Lock() for i, client := range clients { if client == c { clients = append(clients[:i], clients[i+1:]...) break } } mutex.Unlock() }() fmt.Fprintf(c.conn, "Enter a username: ") username, err := bufio.NewReader(c.conn).ReadString('\n') if err != nil { fmt.Println("Error reading username:", err.Error()) return } c.username = username[:len(username)-1] // Broadcast the user's join message to all connected clients msg := fmt.Sprintf("%s has joined the chat!", c.username) mutex.Lock() for _, client := range clients { if client == c { continue } fmt.Fprintln(client.conn, msg) } mutex.Unlock() // Read messages from this client and broadcast them to all connected clients for { msg, err := bufio.NewReader(c.conn).ReadString('\n') if err != nil { fmt.Printf("Error reading from %s: %s\n", c.username, err.Error()) return } msg = fmt.Sprintf("%s: %s", c.username, msg) mutex.Lock() for _, client := range clients { fmt.Fprintln(client.conn, msg) } mutex.Unlock() } }(&Client{conn: conn}) } }Both of these examples use the net package in Go, specifically the TCPListener object.