编辑:我已经解决了我自己的问题并修复了下面的代码以反映这些变化,以防万一有人遇到同样的困难。此代码适用于 PHP 客户端和 Java 服务器连接。
我知道论坛上充斥着这些问题……但是,我已经尝试了几乎所有其他方法超过 8 个小时,但我无计可施。我正在尝试将字符串从 java Socket 发送到 PHP Socket。我是一个 PHP 套接字新手,所以希望有人可以很容易地诊断出我的问题......这是 PHP 代码:
<html>
<head>
</head>
<body>
<?php
//connection to NetworkService in app to manage incoming request
$addr = 'your server address';
$port = 1740;
$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_connect($socket, $addr, $port);
//"\r\n" is very important as it signifies to the server
// that this is the end of the transmission
$request = "message to send \r\n";
//no flags needed circa php 5.2
$sent = socket_sendto($socket, $request, strlen($request), 0 , $addr, $port);
if($sent !== FALSE){
$message = '';
$next = '';
//loop through to continue appending until everything has been read
while($next = socket_read($socket, 4096)){
$message .= $next;
}
echo $message;
} else{
echo "Failed.";
}
socket_close($socket);
?>
</body>
</html>
Java 代码:
public class TestServer{
public static void main(String argv[0]) throws Exception{
String in; String out = "Hello PHP\r\n";
ServerSocket inSock = new ServerSocket(1740);
while(true){
System.out.println("Now accepting connections");
Socket outSock = inSock.accept();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(outSock.getInputStream()));
PrintWriter sender = new PrintWriter(outSock.getOutputStream());
in = bReader.readLine();
System.out.println("Received: " + in);
dWriter.print(out);
System.out.println("Sent: " + out);
}
}
}
问题不在于第一次发送(从 PHP 到 JAVA),而在于第二次发送(响应)只是挂起。Java 代码完全运行,所以我知道问题与 socket_read() 或 socket_recv() 函数有关。我尝试过 sleep() 并尝试使用 socket_setnoblock() 的方法(尽管可能不正确)。正如您在我的“选项:”评论中看到的那样,我在这里也尝试了几种不同的方法,但无济于事。我会错过什么?非常感谢您!