一.服务端
package mainimport ( "fmt" "net"
)
func main ( ) { fmt. Println ( "服务器开始监听..." ) listen, err := net. Listen ( "tcp" , "localhost:8889" ) if err != nil { fmt. Println ( "监听错误:" , err) return } defer listen. Close ( ) fmt. Println ( "listen地址:" , listen. Addr ( ) ) for { conn, err := listen. Accept ( ) if err != nil { fmt. Println ( "接收连接失败:" , err) continue } else { fmt. Println ( "接收连接conn:" , conn. RemoteAddr ( ) ) } go handleConn ( conn) }
} func handleConn ( conn net. Conn) { defer conn. Close ( ) for { fmt. Println ( "等待客户端消息:" ) var bf = make ( [ ] byte , 1024 ) n, err := conn. Read ( bf) if err != nil { fmt. Println ( "服务端读取数据失败:" , err) return } fmt. Println ( "服务端接收数据:" , string ( bf[ : n] ) ) }
}
二.客户端
package mainimport ( "bufio" "fmt" "net" "os" "strings"
)
func main ( ) { conn, err := net. Dial ( "tcp" , "localhost:8889" ) if err != nil { fmt. Println ( "客户端连接服务端错误:" , err) return } defer conn. Close ( ) for { fmt. Println ( "请输入消息(输入exit退出客户端):" ) readString, err := bufio. NewReader ( os. Stdin) . ReadString ( '\n' ) readString = strings. TrimSpace ( readString) if readString == "exit" { break } if err != nil { fmt. Println ( "终端读取数据失败:" , err) continue } else { fmt. Println ( "即将发送数据:" , readString) } n, err := conn. Write ( [ ] byte ( readString) ) if err != nil { fmt. Println ( "发送数据失败:" , err) continue } fmt. Println ( "已发送数据字节数:" , n) } fmt. Println ( "成功退出客户端!!!!!!!" )
}