简体   繁体   English

无法使用PHP客户端从Java套接字服务器读取响应

[英]Cannot read response from Java socket server using PHP client

I have a server written in Java. 我有一台用Java编写的服务器。 Its a simple one that echoes "HELLO" when a client connects and then echoes back any reply the client sends. 它是一种简单的方法,当客户端连接时回显“ HELLO”,然后回显客户端发送的所有回复。 The code is below: 代码如下:

ServerSocket ss=new ServerSocket(2001);
while(true) {
  Socket s=ss.accept();
  BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
  PrintWriter out=new PrintWriter(s.getOutputStream(),true);
  out.println("HELLO");
  String msg=in.readLine();
  out.println(msg);
}

I have a PHP script that connects to the server: 我有一个连接到服务器的PHP脚本:

<?php
  $socket=socket_create(AF_INET,SOCK_STREAM,getprotobyname('tcp'));
  socket_connect($socket,'127.0.0.1',2001);
  $msg=socket_read($socket,10);
  echo socket_write($socket,'I am the client.');
  $msg=socket_read($socket,20);
  echo $msg;
?>

I am getting the "HELLO" message from the server, and the server is also getting the "I am the client" message, but the PHP client is not getting the reply back. 我从服务器收到“ HELLO”消息,服务器也收到“我是客户端”消息,但是PHP客户端没有得到回复。 What am I doing wrong here? 我在这里做错了什么?

in.readLine() won't return until it sees a line terminator. in.readLine()在看到行终止符之前不会返回。

Unless socket_write in PHP implicitly adds a line terminator, you'll need to do so yourself, so that the Java side sees that you've written a complete line of text. 除非PHP中的socket_write隐式添加行终止符,否则您需要自己这样做,以便Java端可以看到您已经编写了完整的文本行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM