Cannot read response from Java socket server using PHP client

自古美人都是妖i 提交于 2019-12-13 03:34:44

问题


I have a server written in Java. Its a simple one that echoes "HELLO" when a client connects and then echoes back any reply the client sends. 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
  $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. What am I doing wrong here?


回答1:


in.readLine() won't return until it sees a line terminator.

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.



来源:https://stackoverflow.com/questions/10667823/cannot-read-response-from-java-socket-server-using-php-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!