Go语言-聊天室2
// chatroom project main.go package main import ( "fmt" "net" ) func ProcessInfo(conn net.Conn) { buf := make([]byte, 1024) defer conn.Close() for { numOfBytes, err := conn.Read(buf) if err != nil { break } if numOfBytes != 0 { remoteAddr := conn.RemoteAddr() fmt.Print(remoteAddr) fmt.Printf("Has received this message: %s\n", string(buf[0:numOfBytes])) } } } func CheckError(err error) { if err != nil { panic(err) } } func main() { listen_socket, err := net.Listen("tcp", "127.0.0.1:8080") CheckError(err) defer listen_socket.Close() fmt.Println("Server is waiting....") for { conn, err := listen_socket.Accept() CheckError(err) go ProcessInfo(conn) } }
// chatroom_client package main import ( "bufio" "fmt" "net" "os" "strings" ) func CheckError(err error) { if err != nil { panic(err) } } func MessageSend(conn net.Conn) { var input string for { reader := bufio.NewReader(os.Stdin) data, _, _ := reader.ReadLine() input = string(data) if strings.ToUpper(input) == "EXIT" { conn.Close() break } _, err := conn.Write([]byte(input)) if err != nil { conn.Close() fmt.Println("client connect failure: " + err.Error()) break } } } func main() { conn, err := net.Dial("tcp", "127.0.0.1:8080") CheckError(err) defer conn.Close() go MessageSend(conn) buf := make([]byte, 1024) for { numOfBytes, err := conn.Read(buf) CheckError(err) fmt.Println("receive server message content:" + string(buf[0:numOfBytes])) } fmt.Println("Client program end!") }