You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.6 KiB

This file contains ambiguous Unicode characters!

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.

package netProgram
import (
"log"
"net"
"time"
)
const tcp = "tcp"
// 服务端
func TcpServer() {
// 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)
if err != nil {
log.Fatalln(err)
}
// 关闭监听
defer listener.Close()
log.Printf("%s server is listening on %s\n", tcp, listener.Addr())
// B. 接受连接请求
// 循环接受
for {
// 阻塞接受
conn, err := listener.Accept()
if err != nil {
log.Println(err)
}
// 处理连接,读写
// 日志连接的远程地址client addr
log.Printf("accept from %s\n", conn.RemoteAddr())
}
}
// 服务端
func TcpBacklogServer() {
// A. 基于某个地址建立监听
// 服务端地址
address := ":5678" // Any IP or version
listener, err := net.Listen(tcp, address)
if err != nil {
log.Fatalln(err)
}
// 关闭监听
defer listener.Close()
log.Printf("%s server is listening on %s\n", tcp, listener.Addr())
// B. 接受连接请求
// 循环接受
for {
// 阻塞接受
conn, err := listener.Accept()
if err != nil {
log.Println(err)
}
// 处理连接,读写
go func(conn net.Conn) {
// 日志连接的远程地址client addr
log.Printf("accept from %s\n", conn.RemoteAddr())
time.Sleep(time.Second)
}(conn)
}
}