我正在尝试从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));
?>
爪哇:
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页面是空白的,这意味着它没有执行任何脚本。那我做错了什么?
答案 0 :(得分:1)
你最后忘记了一个括号:
socket_write($socket, $msg, strlen($msg));
答案 1 :(得分:0)
简单思考。现在只有我得到了答案。如果没有“ \ n”,则新行socket_write不会发送数据。
$msg = "message \n";
您应该换行。