github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/pipes/net/new.go (about)

     1  package net
     2  
     3  import (
     4  	"context"
     5  	"net"
     6  
     7  	"github.com/lmorg/murex/lang/stdio"
     8  	"github.com/lmorg/murex/lang/types"
     9  )
    10  
    11  func init() {
    12  	stdio.RegisterPipe("udp-dial", newDialerUDP)
    13  	stdio.RegisterPipe("tcp-dial", newDialerTCP)
    14  	stdio.RegisterPipe("udp-listen", newListenerUDP)
    15  	stdio.RegisterPipe("tcp-listen", newListenerTCP)
    16  }
    17  
    18  func newDialerUDP(arguments string) (stdio.Io, error) {
    19  	return NewDialer("udp", arguments)
    20  }
    21  
    22  func newDialerTCP(arguments string) (stdio.Io, error) {
    23  	return NewDialer("tcp", arguments)
    24  }
    25  
    26  func newListenerUDP(arguments string) (stdio.Io, error) {
    27  	return NewListener("udp", arguments)
    28  }
    29  
    30  func newListenerTCP(arguments string) (stdio.Io, error) {
    31  	return NewListener("tcp", arguments)
    32  }
    33  
    34  // NewDialer creates a new net.Dial-based stream.Io pipe
    35  func NewDialer(protocol, address string) (n *Net, err error) {
    36  	n = new(Net)
    37  	n.protocol = protocol
    38  
    39  	if protocol == "udp" || protocol == "tcp" {
    40  		n.dataType = types.Generic
    41  	} else {
    42  		protocol = "tcp"
    43  	}
    44  
    45  	n.conn, err = net.Dial(protocol, address)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	n.ctx, n.forceClose = context.WithCancel(context.Background())
    51  
    52  	return
    53  }
    54  
    55  // NewListener creates a new net.Listen-based stream.Io pipe
    56  func NewListener(protocol, address string) (n *Net, err error) {
    57  	n = new(Net)
    58  	n.protocol = protocol
    59  
    60  	if protocol == "udp" || protocol == "tcp" {
    61  		n.dataType = types.Generic
    62  	} else {
    63  		protocol = "tcp"
    64  	}
    65  
    66  	listen, err := net.Listen(protocol, address)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  	defer listen.Close()
    71  
    72  	n.conn, err = listen.Accept()
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  
    77  	n.ctx, n.forceClose = context.WithCancel(context.Background())
    78  
    79  	return
    80  }