tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/net/tcpecho/main.go (about)

     1  // This example listens on port :8080 for client connections.  Bytes
     2  // received from the client are echo'ed back to the client.  Multiple
     3  // clients can connect as the same time, each consuming a client socket,
     4  // and being serviced by it's own go func.
     5  //
     6  // Example test using nc as client to copy file:
     7  //
     8  // $ nc 10.0.0.2 8080 <file >copy ; cmp file copy
     9  
    10  //go:build ninafw || wioterminal
    11  
    12  package main
    13  
    14  import (
    15  	"io"
    16  	"log"
    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  	port string = ":8080"
    28  )
    29  
    30  var buf [1024]byte
    31  
    32  func echo(conn net.Conn) {
    33  	println("Client", conn.RemoteAddr(), "connected")
    34  	defer conn.Close()
    35  	_, err := io.CopyBuffer(conn, conn, buf[:])
    36  	if err != nil && err != io.EOF {
    37  		log.Fatal(err.Error())
    38  	}
    39  	println("Client", conn.RemoteAddr(), "closed")
    40  }
    41  
    42  func main() {
    43  
    44  	time.Sleep(2 * time.Second)
    45  
    46  	link, _ := probe.Probe()
    47  
    48  	err := link.NetConnect(&netlink.ConnectParams{
    49  		Ssid:       ssid,
    50  		Passphrase: pass,
    51  	})
    52  	if err != nil {
    53  		log.Fatal(err)
    54  	}
    55  
    56  	println("Starting TCP server listening on", port)
    57  	l, err := net.Listen("tcp", port)
    58  	if err != nil {
    59  		log.Fatal(err.Error())
    60  	}
    61  	defer l.Close()
    62  
    63  	for {
    64  		conn, err := l.Accept()
    65  		if err != nil {
    66  			log.Fatal(err.Error())
    67  		}
    68  		go echo(conn)
    69  	}
    70  }