简单的tcp server
package main
import (
"fmt"
"net"
)
func main() {
//创建一个用于监听的套接字
listener, err := net.Listen("tcp","127.0.0.1:8000")
if err != nil {
fmt.Println("net listener err:",err)
return
}
defer listener.Close()
fmt.Println("服务器等待客户端连接")
//阻塞监听客户端连接请求,成功建立连接,返回用于通信的socket
conn, err := listener.Accept()
if err != nil {
fmt.Println("listener.Accept() err:",err)
return
}
fmt.Println("服务器与客户端成功建立连接")
defer conn.Close()
buf := make([]byte,4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn read err:",err)
return
}
fmt.Println("服务器读到数据:",string(buf[:n]))
conn.Write(buf[:n])
}
简单的tcp client
package main
import (
"fmt"
"net"
)
func main() {
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("hello"))
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err:",err)
return
}
fmt.Println("服务器回发:",string(buf[:n]))
}
tcp server 并发
package main
import (
"net"
"fmt"
"strings"
)
func HandlerConnect(conn net.Conn) {
defer conn.Close()
//获取连接的客户端 Addr
addr := conn.RemoteAddr()
fmt.Println(addr,"客户端成功连接")
// 读取客户端数据
buf := make([]byte,4096)
for {
n, err := conn.Read(buf)
if n == 0 {
fmt.Println("客户端",addr,"断开连接")
return
}
if err != nil {
fmt.Println("conn.Read err:",err)
return
}
fmt.Println("服务器读到数据",string(buf[:n]),"=========",addr)
// 小写转大写,回发给客户端
conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
}
}
func main() {
listener, err := net.Listen("tcp","127.0.0.1:8001")
if err != nil {
fmt.Println("net.Listen err:",err)
return
}
defer listener.Close()
fmt.Println("服务器等待客户端连接")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("listener.Accpet err:",err)
return
}
go HandlerConnect(conn)
}
}
tcp client并发
package main
import (
"fmt"
"net"
"os"
)
func main() {
conn, err := net.Dial("tcp","127.0.0.1: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 err:",err)
continue
}
conn.Write(str[:n])
}
}()
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err:",err)
return
}
fmt.Println("服务器回发:",string(buf[:n]))
}
}