Go 语言服务器端程序与客户端程序
1.服务器端程序代码
package main
import (
"fmt"
"net"
)
func main() {
listenerFD, err := net.Listen("tcp4", ":8082")
if err != nil {
fmt.Printf("Error:%s 监听失败,端口号:%s\n", err.Error(), "8080")
return
}
defer listenerFD.Close()
for {
clientFD, err := listenerFD.Accept()
if err != nil {
fmt.Printf("接受客户端连接失败:%s\n", err.Error())
}
go func(socketFD net.Conn) {
defer fmt.Println("client end")
defer socketFD.Close()
fmt.Printf("%s\n", socketFD.RemoteAddr().String())
helloWorld := "Hello World!"
n, err := socketFD.Write([]byte(helloWorld))
if err != nil {
fmt.Printf("向连接写数据失败:%s\n", err)
}
if n != len(helloWorld) {
fmt.Printf("向连接写数据失败\n")
}
}(clientFD)
}
fmt.Println("Hello world Programmer Stop!")
}
2.客户端代码:
// client
package main
import (
"fmt"
"net"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(1000)
for i := 0; i < 1000; i++ {
go func() {
for {
clientFd, err := net.DialTimeout("tcp4", "127.0.0.1:8082", 20*time.Second)
if err != nil {
fmt.Printf("错误:客户端连接服务器失败 %s\n", err)
time.Sleep(time.Second)
continue
}
buf := make([]byte, 15)
clientFd.Read(buf)
clientFd.Close()
fmt.Printf("content:%s\n", buf)
time.Sleep(time.Second)
}
wg.Done()
}()
}
wg.Wait()
fmt.Println("client done!")
}
3.运行截图: