Skip to content

Instantly share code, notes, and snippets.

@udhos
Forked from suconghou/nc.go
Created March 28, 2018 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save udhos/58a0bd371f8043d2d1b8ff209947894d to your computer and use it in GitHub Desktop.
Save udhos/58a0bd371f8043d2d1b8ff209947894d to your computer and use it in GitHub Desktop.
nc golang
package main
import (
"fmt"
"io"
"net"
"os"
"sync"
)
const tcp = "tcp"
/**
(this is the right answer)
linux nc command port to golang
in nc , we can do this
echo 'my id is 1' > /tmp/1
echo 'my id is 3' > /tmp/3
rm -rf /tmp/2 /tmp/4
server
nc -l 19090 < /tmp/1 > /tmp/2
( if you are in linux not mac this may be ` nc -l -p 19090 ` )
client
nc 127.0.0.1 19090 < /tmp/3 > /tmp/4
when finish ,both server and client will be closed
client send /tmp/3 is saved by server to /tmp/2
server send /tmp/1 is saved by server to /tmp/4
then use golang do the same thing , but when finished , both server and client can not closed automaticly
echo 'my id is 1' > /tmp/1
echo 'my id is 3' > /tmp/3
rm -rf /tmp/2 /tmp/4
./nc serer < /tmp/1 > /tmp/2
./nc < /tmp/3 > /tmp/4
**/
func main() {
if len(os.Args) > 1 {
fmt.Fprintf(os.Stderr, "run as server\n")
server()
} else {
fmt.Fprintf(os.Stderr, "run as client\n")
client()
}
}
func server() error {
port := "19088"
l, err := net.Listen(tcp, ":"+port)
if err != nil {
return err
}
defer l.Close()
conn, err := l.Accept()
if err != nil {
return err
}
var wg sync.WaitGroup
wg.Add(2)
tcpconn := conn.(*net.TCPConn)
go func() {
io.Copy(tcpconn, os.Stdin)
fmt.Fprintln(os.Stderr, "os.Stdin 2 conn done")
tcpconn.CloseWrite()
wg.Done()
}()
go func() {
io.Copy(os.Stdout, tcpconn)
fmt.Fprintln(os.Stderr, "conn 2 os.Stdout done")
tcpconn.CloseRead()
wg.Done()
}()
wg.Wait()
return nil
}
func client() error {
addr := "127.0.0.1:19088"
conn, err := net.Dial(tcp, addr)
if err != nil {
return err
}
tcpconn := conn.(*net.TCPConn)
var wg sync.WaitGroup
wg.Add(2)
go func() {
io.Copy(tcpconn, os.Stdin)
fmt.Fprintln(os.Stderr, "conn 2 os.Stdin done")
tcpconn.CloseWrite()
wg.Done()
}()
go func() {
io.Copy(os.Stdout, tcpconn)
fmt.Fprintln(os.Stderr, "os.Stdout 2 conn done")
tcpconn.CloseRead()
wg.Done()
}()
wg.Wait()
return nil
}
@hothanhloc68
Copy link

``$ psql
Timing is on.
Null display is "∅".
Line style is unicode.
psql (14.5 (Homebrew))
Type "help" for help.

jack@[local]:5432 jack=#

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment