服务器访问

aaa777 · · 1386 次点击
服务器: ```go package main import ( "bufio" "flag" "fmt" "net" "os" "strconv" "sync" ) var host = flag.String("host", "39.108.1.61", "host") var port = flag.String("port", "7758", "port") func main() { flag.Parse() conn, err := net.Dial("tcp", *host+":"+*port) if err != nil { fmt.Println("Error connecting:", err.Error()) os.Exit(1) } defer conn.Close() fmt.Println("Connecting to " + *host + ":" + *port) var wg sync.WaitGroup wg.Add(2) go handleWrite(conn, &wg) go handleRead(conn, &wg) wg.Wait() } func handleWrite(conn net.Conn, wg *sync.WaitGroup) { defer wg.Done() for i := 10; i > 0; i-- { _, e := conn.Write([]byte("hello " + strconv.Itoa(i) + "\r\n")) if e != nil { fmt.Println("Error to send message because of ", e.Error()) break } } } func handleRead(conn net.Conn, wg *sync.WaitGroup) { defer wg.Done() reader := bufio.NewReader(conn) for i := 1; i <= 10; i++ { line, err := reader.ReadString(byte('\n')) if err != nil { fmt.Print("Error to read message because of ", err) return } fmt.Print(line) } } ``` 客户端: ```go package main import ( "flag" "fmt" "io" "net" "os" ) var host = flag.String("host", "39.108.1.61", "host") var port = flag.String("port", "7758", "port") func main() { flag.Parse() var l net.Listener var err error l, err = net.Listen("tcp", *host+":"+*port) if err != nil { fmt.Println("Error listening:", err) os.Exit(1) } defer l.Close() fmt.Println("Listening on " + *host + ":" + *port) for { conn, err := l.Accept() if err != nil { fmt.Println("Error accepting: ", err) os.Exit(1) } //logs an incoming message fmt.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr()) // Handle connections in a new goroutine. go handleRequest(conn) } } func handleRequest(conn net.Conn) { defer conn.Close() for { io.Copy(conn, conn) } } ```
#12
更多评论
这是啥意思,代理?
#1
就是给了你一个ip和端口,也可以说是代理
#2