C:\Users\bob\golang5>go run main.go
hi from server~
C:\Users\bob\golang5>go run main.go
hi from server~
C:\Users\bob\golang5>go run main.go
hi from server~
C:\Users\bob\golang5>go run main.go
hi from server~
//cmd - server
C:\Users\bob\golang4>go run main.go
hello from client~0
hello from client~1
hello from client~2
hello from client~3
//client main.go
package main
import (
"fmt"
"io/ioutil"
"net"
)
func main() {
conn, err := net.Dial("tcp", "192.168.0.18:9000")
if err != nil {
panic(err)
}
defer conn.Close()
_, err = conn.Write([]byte("hello from client~"))
if err != nil {
panic(err)
}
bs, _ := ioutil.ReadAll(conn)
message := string(bs)
fmt.Println(message)
if string(message[len(message)-1]) == "~" {
conn.Close()
}
}
------------------------
//server main.go
package main
import (
"fmt"
"net"
"strconv"
)
func main() {
ln, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
defer ln.Close()
for i := 0; ; i++ {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
for {
bs := make([]byte, 1024)
n, err := conn.Read(bs)
if err != nil {
break
}
if string(bs[n-1]) == "~" {
_, err = conn.Write([]byte("hi from server~"))
if err != nil {
panic(err)
break
}
fmt.Println(string(bs[:n]) + strconv.Itoa(i))
conn.Close()
break
}
//_, err = conn.Write(bs[:n])
_, err = conn.Write([]byte("_"))
if err != nil {
break
}
fmt.Print(string(bs[:n]))
}
conn.Close()
}
}
reference:
No comments:
Post a Comment