参考的这位大佬的:https://blog.csdn.net/wowzai/article/details/9936659
但是这个实际上服务器不会echo回去。所以我写了个带echo回去的版本。
server
package main
import (
"net"
"os"
"fmt"
"io"
"bufio"
)
func handleConn(tcpConn *net.TCPConn) {
if tcpConn == nil {
return
}
:= bufio.NewReader(tcpConn)
inputReader for {
, err := inputReader.ReadString('\n')
inputif err == io.EOF {
.Printf("The RemoteAddr:%s is closed!\n", tcpConn.RemoteAddr().String())
fmtreturn
}
(err)
handleErrorif input == "exit" {
.Printf("The client: %s has exited\n", tcpConn.RemoteAddr().String())
fmt}
.Printf("Read:%s", input)
fmt.Write([]byte(input))
tcpConn}
}
func handleError(err error) {
if err == nil {
return
}
.Printf("error:%s\n", err.Error());
fmt// TODO: Make it more robust
.Exit(1)
os}
func main() {
if len(os.Args) != 2 {
.Println("Usage: %s <port>", os.Args[0]);
fmtreturn
}
:= os.Args[1]
port , err := net.ResolveTCPAddr("tcp4", "localhost:" + port)
tcpAddr(err)
handleError, err := net.ListenTCP("tcp4", tcpAddr)
tcpListener(err)
handleErrordefer tcpListener.Close()
for {
, err := tcpListener.AcceptTCP()
tcpConn.Printf("The client:%s has connected!\n", tcpConn.RemoteAddr().String())
fmt(err)
handleErrordefer tcpConn.Close()
go handleConn(tcpConn)
}
}
client
package main
import (
"net"
"fmt"
"os"
"bufio"
)
func handleError(err error) {
if err == nil {
return
}
.Printf("error:%s\n", err.Error());
fmt// TODO: Make it more robust
.Exit(1)
os}
func main() {
, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:5188")
tcpAddr, err := net.DialTCP("tcp", nil, tcpAddr)
connif err != nil {
.Println("server is not starting")
fmtreturn
}
defer conn.Close()
for {
:= bufio.NewReader(os.Stdin)
inputReader , err := inputReader.ReadString('\n')
input(err)
handleError.Print("client send: ", input)
fmt:= []byte(input)
b .Write(b)
conn:= bufio.NewReader(conn)
echoReader , err := echoReader.ReadString('\n')
echo(err)
handleError.Print("Server echo: ", echo)
fmt}
}