Last active
October 12, 2023 14:30
-
-
Save suconghou/a1bfab9a30b3408400b6382d73051227 to your computer and use it in GitHub Desktop.
nc golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment