1、服务端:
package main
import (
"fmt"
"net"
"sync"
)
type ChatServer struct {
clients map[string]net.Conn
clientsMux sync.Mutex
}
func NewChatServer() *ChatServer {
return &ChatServer{
clients: make(map[string]net.Conn),
}
}
func (s *ChatServer) broadcast(message string, sender string) {
s.clientsMux.Lock()
defer s.clientsMux.Unlock()
for clientAddr, conn := range s.clients {
if clientAddr != sender {
fmt.Fprintf(conn, "[%s]: %s\n", sender, message)
}
}
}
func (s *ChatServer) handleConnection(conn net.Conn) {
defer conn.Close()
clientAddr := conn.RemoteAddr().String()
fmt.Printf("New connection from %s\n", clientAddr)
s.clientsMux.Lock()
s.clients[clientAddr] = conn
s.clientsMux.Unlock()
for {
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
fmt.Printf("Error reading from %s: %v\n", clientAddr, err)
break
}
message := string(buffer[:n])
fmt.Printf("[%s]: %s\n", clientAddr, message)
s.broadcast(message, clientAddr)
}
}
func main() {
server := NewChatServer()
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error:", err)
return
}
defer listener.Close()
fmt.Println("TCP chat server listening on :8080")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go server.handleConnection(conn)
}
}
2、客户端:
package main
import (
"bufio"
"fmt"
"net"
"os"
)
func readMessages(conn net.Conn) {
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading message:", err)
break
}
fmt.Print(message)
}
}
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8080")
if err != nil {
fmt.Println("Error connecting to server:", err)
return
}
defer conn.Close()
go readMessages(conn)
for {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
message := scanner.Text()
_, err := conn.Write([]byte(message + "\n"))
if err != nil {
fmt.Println("Error sending message:", err)
break
}
}
}