在Golang服务器中接受持久的TCP连接

编程入门 行业动态 更新时间:2024-10-25 04:19:31
本文介绍了在Golang服务器中接受持久的TCP连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试Go-并希望创建一个可以远程登录,发送命令并接收响应的TCP服务器。

I am experimenting with Go - and would like to create a TCP server which I can telnet to, send commands and receive responses.

const ( CONN_HOST = "localhost" CONN_PORT = "3333" CONN_TYPE = "tcp" ) func main() { listener, err := net.Listen(CONN_TYPE, fmt.Sprintf("%s:%s", CONN_HOST, CONN_PORT)) if err != nil { log.Panicln(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { log.Panicln(err) } go handleRequest(conn) } } func handleRequest(conn net.Conn) { buffer := make([]byte, 1024) length, err := conn.Read(buffer) if err != nil { log.Panicln(err) } str := string(buffer[:length]) fmt.Println(conn.RemoteAddr().String()) fmt.Printf("Received command %d\t:%s\n", length, str) switch str { case "PING\r\n": sendResponse("PONG", conn) case "PUSH\r\n": sendResponse("GOT PUSH", conn) default: conn.Write([]byte(fmt.Sprintf("UNKNOWN_COMMAND: %s\n", str))) } conn.Close() // closes the connection } func sendResponse(res string, conn net.Conn) { conn.Write([]byte(res+"\n")) }

以上代码段每次都会关闭连接,将我踢出终端会话。但是我真正想要的是能够保持连接打开以进行更多的I / O操作。如果我只是删除 conn.Close(),则服务器似乎挂在某个地方,因为它没有更多响应。

The above snippet will close the connection every time, kicking me out of the terminal session. But what I actually want, is to be able to keep the connection open for more I/O operations. If I simply remove the conn.Close(), then the server appears to hang somewhere as it does not get any more responses.

我已解决的方法是让我的handleRequest方法无限循环,以便它在收到 QUIT\r\n 消息之前不会退出。这是否合适-还是有更好的实现方法?

The way I have resolved this is to have my handleRequest method endlessly loop so that it never exits till it receives a QUIT\r\n message. Is this appropriate - or is there a better way of achieving?

func handleRequest(conn net.Conn) { for { log.Println("Handling Request") buffer := make([]byte, 1024) length, err := conn.Read(buffer) if err != nil { log.Panicln(err) } str := string(buffer[:length]) fmt.Println(conn.RemoteAddr().String()) fmt.Printf("Received command %d\t:%s\n", length, str) switch str { case "PING\r\n": sendResponse("PONG", conn) case "PUSH\r\n": sendResponse("GOT PUSH", conn) case "QUIT\r\n": sendResponse("Goodbye", conn) conn.Close() default: conn.Write([]byte(fmt.Sprintf("UNKNOWN_COMMAND: %s\n", str))) } } }

推荐答案

您的第二个循环示例已经是您想要的。您只需简单地循环并读取所需的时间(或可能直到一些读/写超时或外部取消信号)。

Your second example with the loop is already what you want. You simply loop and read as long as you want (or probably until some read/write timeout or an external cancellation signal).

但是它仍然有错误: TCP为您提供了一个字节流,其中不能保证从一侧进行一次写操作将在另一侧以相同的数据长度完全产生一次读操作。这意味着,如果客户端写 PING\r\n ,则您在初次阅读中仍然只能收到 PI 。您可以使用 bufio.Scanner 来解决此问题,并始终读取到第一行换行符。

However it still has an error in it: TCP gives you a stream of bytes, where it is not guaranteed that one write from a side will yield exactly one read on the other side with the same data length. This means if the client writes PING\r\n you could still receive only PI in the first read. You could fix that by using a bufio.Scanner and always read up to the first newline.

更多推荐

在Golang服务器中接受持久的TCP连接

本文发布于:2023-10-15 00:53:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492757.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:持久   器中   Golang   TCP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!