聊天系统-客户端
package main
import (
"fmt"
"log"
"net"
"os"
)
func main() {
Start(os.Args[1])
}
func Start(tcpAddrStr string) {
tcpAddr, err := net.ResolveTCPAddr("tcp4", tcpAddrStr)
if err != nil {
log.Printf("Resolve tcp addr failed:%v\n", err)
return
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
log.Printf("Dial to server failed:%v\n", err)
return
}
SendMsg(conn)
buf := make([]byte, 1024)
for {
length, err := conn.Read(buf)
if err != nil {
log.Printf("recv server mag failed:%v\n", err)
conn.Close()
os.Exit(0)
break
}
fmt.Println(string(buf[0:length]))
}
}
func SendMsg(conn net.Conn) {
username := "碧萝"
for {
var input string
fmt.Scanln(&input)
if input == "/q" || input == "/quit" {
fmt.Println("Byebye ...")
conn.Close()
os.Exit(0)
}
if len(input) > 0 {
msg := username + " say: " + input
_, err := conn.Write([]byte(msg))
if err != nil {
conn.Close()
break
}
}
}
}