我正在尝试在PHP套接字和JAVA套接字之间传输简单消息。 php套接字成功发送数据并等待Java服务器响应。但另一方面,Java服务器的套接字仍在等待来自PHP的消息。
以下是Java代码:
ServerSocket s = new ServerSocket(4280);
Socket sock = s.accept();
System.out.println("Connected");
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
System.out.println("Reading");
String str = br.readLine();
System.out.println("Writing");
bw.write(str);
输出:
连接
阅读
以下是PHP代码:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, "localhost", 4280);
socket_write($socket, "Hello");
echo socket_read($socket, 10);
socket_write($socket, "Lelo");
echo socket_read($socket, 10);
输出:
浏览器:等待localhost
答案 0 :(得分:2)
通常会导致问题的两件事:
readLine()
方法,但您没有发送linefeed
并返回PHP代码。<强>代码:强>
添加换行符:
socket_write($socket, "Hello\r\n");
答案 1 :(得分:0)
String str = br.readLine();
期望PHP程序不会发送\n
。
添加:
socket_write($socket, "Hello\n" ); // <<<=== '\n' added