gpt4 book ai didi

PHP/Go 套接字通信

转载 作者:数据小太阳 更新时间:2023-10-29 03:41:29 26 4
gpt4 key购买 nike

我正在尝试使用套接字在 Go 和 PHP 之间进行通信。我使用的代码是:

开始:

fmt.Println("Launching server...")
ln, _ := net.Listen("tcp", ":8080")
conn, _ := ln.Accept()

for {
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message Received:", string(message))
conn.Write([]byte("test" +"\n"))

}

PHP:

$address = gethostbyaddr($ip);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if($socket === false){
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error());
}

$result = socket_connect($socket, $address, $port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket));
}
socket_write($socket, "test", 4);
socket_read($socket, 4);

问题是 Go 服务器一直认为它一直在接收某些东西,所以它不断地打印“消息已收到:”。如果我这样做 if(message!="") 它有点工作,但 cpu 使用率很高。

另一个问题是服务器不会收到“测试”,除非我注释掉 socket_read($socket, 4);在 PHP 中。

最佳答案

documentation对于 ReadString 说:

If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF).

这意味着您将获得 io.EOF(表示没有更多数据可从连接中读取)和一个空字符串。

如果您想在没有可用数据时阻塞 ReadString,请不要使用 bufio,而是直接从连接中读取。

另请参阅:documentation对于 net.Conn

Another problem is that the server doesn't receive "test" unless i comment out the socket_read($socket, 4); in PHP.

描述的是here , socket_write 缓冲区:

socket_write() does not necessarily write all bytes from the given buffer. [...]

使用

fflush($socket);

写入后。

关于PHP/Go 套接字通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29963401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com