tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/net/tcpclient/main.go (about) 1 // This example opens a TCP connection and sends some data, for the purpose of 2 // testing speed and connectivity. 3 // 4 // You can open a server to accept connections from this program using: 5 // 6 // nc -lk 8080 7 8 //go:build ninafw || wioterminal || challenger_rp2040 || pico 9 10 package main 11 12 import ( 13 "bytes" 14 "fmt" 15 "log" 16 "machine" 17 "net" 18 "time" 19 20 "tinygo.org/x/drivers/netlink" 21 "tinygo.org/x/drivers/netlink/probe" 22 ) 23 24 var ( 25 ssid string 26 pass string 27 addr string = "10.0.0.100:8080" 28 ) 29 30 var buf = &bytes.Buffer{} 31 32 func main() { 33 34 waitSerial() 35 36 link, _ := probe.Probe() 37 38 err := link.NetConnect(&netlink.ConnectParams{ 39 Ssid: ssid, 40 Passphrase: pass, 41 }) 42 if err != nil { 43 log.Fatal(err) 44 } 45 46 for { 47 sendBatch() 48 time.Sleep(500 * time.Millisecond) 49 } 50 } 51 52 func sendBatch() { 53 54 // make TCP connection 55 message("---------------\r\nDialing TCP connection") 56 conn, err := net.Dial("tcp", addr) 57 for ; err != nil; conn, err = net.Dial("tcp", addr) { 58 message(err.Error()) 59 time.Sleep(5 * time.Second) 60 } 61 62 n := 0 63 w := 0 64 start := time.Now() 65 66 // send data 67 message("Sending data") 68 69 for i := 0; i < 1000; i++ { 70 buf.Reset() 71 fmt.Fprint(buf, 72 "\r---------------------------- i == ", i, " ----------------------------"+ 73 "\r---------------------------- i == ", i, " ----------------------------") 74 if w, err = conn.Write(buf.Bytes()); err != nil { 75 println("error:", err.Error(), "\r") 76 break 77 } 78 n += w 79 } 80 81 buf.Reset() 82 ms := time.Now().Sub(start).Milliseconds() 83 fmt.Fprint(buf, "\nWrote ", n, " bytes in ", ms, " ms\r\n") 84 message(buf.String()) 85 86 if _, err := conn.Write(buf.Bytes()); err != nil { 87 println("error:", err.Error(), "\r") 88 } 89 90 println("Disconnecting TCP...") 91 conn.Close() 92 } 93 94 func message(msg string) { 95 println(msg, "\r") 96 } 97 98 // Wait for user to open serial console 99 func waitSerial() { 100 for !machine.Serial.DTR() { 101 time.Sleep(100 * time.Millisecond) 102 } 103 }