This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
packagenetProgram
import(
"log"
"net"
"time"
)
consttcp="tcp"
// 服务端
funcTcpServer(){
// A. 基于某个地址建立监听
// 服务端地址
//address := "127.0.0.1:5678"
// 端口省略,会使用随机端口
//address := "127.0.0.1:"
// IP省略,使用服务器全部的可用IP
// tcp协议类型
//address := "127.0.0.1:5678" // IPv4
//address := "[::1]:5678" // IPv6
address:=":5678"// Any IP or version
listener,err:=net.Listen(tcp,address)
iferr!=nil{
log.Fatalln(err)
}
// 关闭监听
deferlistener.Close()
log.Printf("%s server is listening on %s\n",tcp,listener.Addr())
// B. 接受连接请求
// 循环接受
for{
// 阻塞接受
conn,err:=listener.Accept()
iferr!=nil{
log.Println(err)
}
// 处理连接,读写
// 日志连接的远程地址(client addr)
log.Printf("accept from %s\n",conn.RemoteAddr())
}
}
// 服务端
funcTcpBacklogServer(){
// A. 基于某个地址建立监听
// 服务端地址
address:=":5678"// Any IP or version
listener,err:=net.Listen(tcp,address)
iferr!=nil{
log.Fatalln(err)
}
// 关闭监听
deferlistener.Close()
log.Printf("%s server is listening on %s\n",tcp,listener.Addr())