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