frp/tests/mock/echo_server.go

127 lines
1.9 KiB
Go
Raw Normal View History

2018-07-11 23:27:47 +08:00
package mock
2016-05-17 19:13:37 +08:00
import (
"fmt"
"io"
"net"
"os"
"syscall"
2016-05-17 19:13:37 +08:00
frpNet "github.com/fatedier/frp/utils/net"
2016-05-17 19:13:37 +08:00
)
2018-07-11 23:27:47 +08:00
func StartTcpEchoServer(port int) {
l, err := frpNet.ListenTcp("127.0.0.1", port)
2016-05-17 19:13:37 +08:00
if err != nil {
fmt.Printf("echo server listen error: %v\n", err)
return
}
for {
c, err := l.Accept()
if err != nil {
fmt.Printf("echo server accept error: %v\n", err)
return
}
go echoWorker(c)
}
}
2018-07-11 23:27:47 +08:00
func StartTcpEchoServer2(port int) {
l, err := frpNet.ListenTcp("127.0.0.1", port)
2018-05-23 14:39:12 +08:00
if err != nil {
fmt.Printf("echo server2 listen error: %v\n", err)
return
}
for {
c, err := l.Accept()
if err != nil {
fmt.Printf("echo server2 accept error: %v\n", err)
return
}
go echoWorker2(c)
}
}
2018-07-11 23:27:47 +08:00
func StartUdpEchoServer(port int) {
l, err := frpNet.ListenUDP("127.0.0.1", port)
2017-03-28 00:27:30 +08:00
if err != nil {
fmt.Printf("udp echo server listen error: %v\n", err)
return
}
for {
c, err := l.Accept()
if err != nil {
fmt.Printf("udp echo server accept error: %v\n", err)
return
}
go echoWorker(c)
}
}
2018-07-11 23:27:47 +08:00
func StartUnixDomainServer(unixPath string) {
os.Remove(unixPath)
syscall.Umask(0)
l, err := net.Listen("unix", unixPath)
if err != nil {
fmt.Printf("unix domain server listen error: %v\n", err)
return
}
for {
c, err := l.Accept()
if err != nil {
fmt.Printf("unix domain server accept error: %v\n", err)
return
}
go echoWorker(c)
}
}
2017-03-09 02:03:47 +08:00
func echoWorker(c net.Conn) {
2017-12-16 23:59:46 +08:00
buf := make([]byte, 2048)
2016-05-17 19:13:37 +08:00
for {
2017-12-16 23:59:46 +08:00
n, err := c.Read(buf)
2016-05-17 19:13:37 +08:00
if err != nil {
2017-12-16 23:59:46 +08:00
if err == io.EOF {
c.Close()
break
} else {
fmt.Printf("echo server read error: %v\n", err)
return
}
2016-05-17 19:13:37 +08:00
}
2017-12-16 23:59:46 +08:00
c.Write(buf[:n])
2016-05-17 19:13:37 +08:00
}
}
2018-05-23 14:39:12 +08:00
func echoWorker2(c net.Conn) {
buf := make([]byte, 2048)
for {
n, err := c.Read(buf)
if err != nil {
if err == io.EOF {
c.Close()
break
} else {
fmt.Printf("echo server read error: %v\n", err)
return
}
}
var w []byte
w = append(w, buf[:n]...)
w = append(w, buf[:n]...)
c.Write(w)
}
}