[英]Socket echo server in go
I'm trying to implement a simple socket echo server in go this is the code: 我正在尝试实现一个简单的套接字echo服务器,这是代码:
package main
import (
"fmt"
"net"
"sync"
)
func echo_srv(c net.Conn, wg sync.WaitGroup) {
defer c.Close()
defer wg.Done()
for {
var msg []byte
n, err := c.Read(msg)
if err != nil {
fmt.Printf("ERROR: read\n")
fmt.Print(err)
return
}
fmt.Printf("SERVER: received %v bytes\n", n)
n, err = c.Write(msg)
if err != nil {
fmt.Printf("ERROR: write\n")
fmt.Print(err)
return
}
fmt.Printf("SERVER: sent %v bytes\n", n)
}
}
func main() {
var wg sync.WaitGroup
ln, err := net.Listen("unix", "./sock_srv")
if err != nil {
fmt.Print(err)
return
}
defer ln.Close()
conn, err := ln.Accept()
if err != nil {
fmt.Print(err)
return
}
wg.Add(1)
go echo_srv(conn, wg)
wg.Wait()
}
For some reason as soon as a client connects, c.Read() does not block and the error message is printed. 出于某种原因,只要客户端连接,c.Read()就不会阻止并打印错误消息。 So, my first question is: Shouldn't c.Read() block until a client sends something to the socket?
所以,我的第一个问题是:在客户端向套接字发送内容之前,是否应该阻止c.Read()阻塞?
And second: After printing the error message, the server does not terminate. 第二:打印错误消息后,服务器不会终止。 This is what I see when executing the program in gdb:
这是我在gdb中执行程序时看到的:
(gdb) run
Starting program: src/sockets/server/server
warning: Could not load shared library symbols for linux-vdso.so.1.
Do you need "set solib-search-path" or "set sysroot"?
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/libthread_db.so.1".
[New Thread 0x7fffe7806700 (LWP 28594)]
[New Thread 0x7fffe7005700 (LWP 28595)]
ERROR: read
EOF^C
Program received signal SIGINT, Interrupt.
runtime.epollwait () at /usr/lib/go/src/pkg/runtime/sys_linux_amd64.s:383
383 RET
(gdb) info goroutines
1 waiting runtime.park
2 syscall runtime.goexit
* 3 syscall runtime.entersyscallblock
I have similar echo servers in Python and C and they work fine. 我在Python和C中有类似的echo服务器,它们工作正常。 For completeness I also post the socket client application below (it works fine with my C and Python servers).
为了完整性,我还发布了下面的套接字客户端应用程序(它适用于我的C和Python服务器)。
Client: 客户:
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
stdin := bufio.NewReader(os.Stdin)
conn, err := net.Dial("unix", "./sock_srv")
if err != nil {
fmt.Print(err)
return
}
defer conn.Close()
for {
fmt.Print("Enter message to transmit: ")
msg, err := stdin.ReadString('\n')
if err != nil {
fmt.Print(err)
return
}
msg = msg[:len(msg)-1]
if (strings.ToLower(msg) == "quit") || (strings.ToLower(msg) == "exit") {
fmt.Println("bye")
return
}
n, err := conn.Write([]byte(msg))
if err != nil {
fmt.Print(err)
return
}
fmt.Printf("CLIENT: sent %v bytes\n", n)
n, err = conn.Read([]byte(msg))
if err != nil {
fmt.Print(err)
return
}
fmt.Printf("CLIENT: received %v bytes\n", n)
fmt.Println("Received message:", msg)
}
}
Here is a working echo_srv
for you. 这是一个有效的
echo_srv
。 You'll need @jnml's suggestion too! 你也需要@ jnml的建议!
only write the bytes received with msg[:n]
只写下用
msg[:n]
收到的字节
func echo_srv(c net.Conn, wg *sync.WaitGroup) { defer c.Close() defer wg.Done() for { msg := make([]byte, 1000) n, err := c.Read(msg) if err == io.EOF { fmt.Printf("SERVER: received EOF (%d bytes ignored)\\n", n) return } else if err != nil { fmt.Printf("ERROR: read\\n") fmt.Print(err) return } fmt.Printf("SERVER: received %v bytes\\n", n) n, err = c.Write(msg[:n]) if err != nil { fmt.Printf("ERROR: write\\n") fmt.Print(err) return } fmt.Printf("SERVER: sent %v bytes\\n", n) } }
I did not check if it's the culprit, but on the "technical analysis" side I noticed one error in your code: You're passing a copy of a sync.Workgroup
to echo_srv
. 我没有检查它是否是罪魁祸首,但在“技术分析”方面,我发现你的代码中有一个错误:你正在将
sync.Workgroup
的副本传递给echo_srv
。 Any changes made to the copy are not effective to the original instance. 对副本所做的任何更改都不会对原始实例生效。
Change the signature of echo
to: 将
echo
的签名更改为:
func echo_srv(c net.Conn, wg *sync.WaitGroup)
and then call it like: 然后称之为:
go echo_srv(conn, &wg)
On a side note: Underscores ( _
) are not used in the middle of idiomatic Go code names. 旁注:在惯用的Go代码名称中间不使用下划线(
_
)。 The idiomatic name would be eg. 惯用名称将是例如。
echoSrv
instead. 而是
echoSrv
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.