gpt4 book ai didi

java - PHP socket_write 不工作

转载 作者:行者123 更新时间:2023-12-02 11:58:41 25 4
gpt4 key购买 nike

我正在尝试从 PHP 脚本向 Java 服务器发送一条简单的消息,并且所有内容都可以很好地相互连接,直到我尝试在 PHP 上使用 socket_write 。如果我尝试,整个脚本就会停止工作,这些事情也应该在socket_write之前发生。这是我的代码:

PHP:

set_time_limit(0);
ob_implicit_flush();

$address = "localhost";
$port = 9999;


if(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "Failed creating socket: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "Socket created" . "\n";
}

if ($result = socket_connect($socket, $address, $port) === false) {
echo "\nFailed connecting to server: " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "Connected" . "\n";
}

$msg = "message"

socket_write($socket, $msg, strlen($msg));

?>

Java:

public class Server {

private static ServerSocket server;
private static Socket connection;
private static InputStream input;
private static BufferedReader br;
private static String message;

public static void main(String[] args) {
Server();
}

public static void Server() {
try {
server = new ServerSocket(9999, 100);
log("Socket created");
} catch (IOException e) {
log("Error creating ServerSocket: " + e.getMessage());
}

while(true) {
try {
log("Waiting for connections...");
connection = server.accept();
log("Connection accepted");
} catch (IOException e) {
log("Error creating connection: " + e.getMessage());
}


try {
log("Setting inputStream..");
input = connection.getInputStream();
log("Connections setup");
} catch (IOException e) {
log("Error creating input stream: " + e.getMessage());
}

br = new BufferedReader(new InputStreamReader(input));

try {
if((message = br.readLine()) != null) {
log(message);
}
} catch (IOException e) {
log("Error reading input: " + e.getMessage());
}
}







}

public static void log(String message) {
System.out.println(message);
}

}

当socket_write被注释时,PHP脚本的页面显示如下:

Socket created

Connected

java 日志显示如下:

Socket created
Waiting for connections...
Connection accepted
Setting inputStream..
Connections setup
Waiting for connections...

这是有道理的,因为没有消息要读取,所以它等待另一个连接。

但是socket_write没有注释,Java日志显示“等待连接”并且PHP页面是空白的,这意味着它没有执行任何脚本。那么我做错了什么?

最佳答案

你忘记了最后的括号:

socket_write($socket, $msg, strlen($msg));

关于java - PHP socket_write 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47417305/

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