1.服务器监听TCP请求
package main
import (
"fmt"
"net"
)
func main01() {
listener, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("net.Listen err:", err)
return
}
defer listener.Close()
fmt.Println("服务器等待客户端建立连接...")
conn, err := listener.Accept()
if err != nil {
fmt.Println("listener.Accept() err:", err)
return
}
defer conn.Close()
fmt.Println("服务器与客户端成功建立连接!!!")
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err:", err)
return
}
conn.Write(buf[:n])
fmt.Println("服务器读到数据:", string(buf[:n]))
}
2.客户端发送TCP请求
package main
import (
"fmt"
"net"
)
func main02() {
conn, err := net.Dial("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("net.Dial err:", err)
return
}
defer conn.Close()
conn.Write([]byte("Are you Ready?"))
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err:", err)
return
}
fmt.Println("服务器回发:", string(buf[:n]))
}
3.CS并发服务器
package main
import (
"fmt"
"net"
"strings"
)
func HandlerConnect(conn net.Conn) {
defer conn.Close()
addr := conn.RemoteAddr()
fmt.Println(addr, "客户端成功连接!")
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if "exit\n" == string(buf[:n]) || "exit\r\n" == string(buf[:n]) {
fmt.Println("服务器接收的客户端退出请求,服务器关闭")
return
}
if n == 0 {
fmt.Println("服务器检测到客户端已关闭,断开连接!!!")
return
}
if err != nil {
fmt.Println("conn.Read err:", err)
return
}
fmt.Println("服务器读到数据:", string(buf[:n]))
conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
}
}
func main03() {
listener, err := net.Listen("tcp", "192.168.15.78:8001")
if err != nil {
fmt.Println("net.Listen err:", err)
return
}
defer listener.Close()
for {
fmt.Println("服务器等待客户端连接...")
conn, err := listener.Accept()
if err != nil {
fmt.Println("listener.Accept err:", err)
return
}
go HandlerConnect(conn)
}
}
4.CS并发客户端
package main
import (
"fmt"
"net"
"os"
)
func main04() {
conn, err := net.Dial("tcp", "192.168.15.78:8001")
if err != nil {
fmt.Println("net.Dial err:", err)
return
}
defer conn.Close()
go func() {
str := make([]byte, 4096)
for {
n, err := os.Stdin.Read(str)
if err != nil {
fmt.Println("os.Stdin.Read err:", err)
continue
}
conn.Write(str[:n])
}
}()
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if n == 0 {
fmt.Println("检查到服务器关闭,客户端也关闭")
return
}
if err != nil {
fmt.Println("conn.Read err:", err)
return
}
fmt.Println("客户端读到服务器回发:", string(buf[:n]))
}
}