Socket编程 php 与 java 通信 问题

服务器端用java线程写Socket
备注:其他无关代码不发了,主要部分发下
System.out.println("Socket["+this.server_id+"] connection success.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter( this.server_socket.getOutputStream())),true);
out.println("Socket["+this.server_id+"] welcome client");
BufferedReader in = new BufferedReader( new InputStreamReader( this.server_socket.getInputStream()));

String ss;
ss = in.readLine();
out.println("test_outputs");

下面是PHP WEB 客户端代码:
$fp = fsockopen("192.168.0.119",5000,$errno,$errstr,30);
stream_set_timeout($fp,30);
stream_set_blocking( $fp , true );
if( !$fp )
{
die("error ".$errstr." ".$errno);
}
else
{
echo ($tmp = fgets($fp))."<br>";
$status = stream_get_meta_data( $fp ) ;
//发送数据超时
if( $status['timed_out'] )
{
echo "read 1 time out" ;
fclose( $fp );
die();
}

echo "link success!"."<br>";
}

fputs($fp,"order1");
echo "fputs order1";

$tmp = fgets($fp);

$status = stream_get_meta_data( $fp );
//发送数据超时
if( $status['timed_out'] )
{
echo "read 2 time out" ;
fclose( $fp );
die();
}

问题:客户端在读取服务器端发过来数据后又发送了数据过去,然后又读取服务器端发来的数据,为什么两个读取中间夹一个发送数据,第2个读取一直读不到,一直超时,无论等多少时间都超时。是不是有什么机制在?请高手回答
分数没有太多,因为自己没怎么去解答问题。请高手见谅
最新回答
失意的片刻

2024-05-13 07:04:26

看不懂php

但是我觉得你这个问题可能是因为php发生的EOF不符合java标准。或者根本没有发送EOF标识。

超时应该发生在 ss = in.readLine();这一行代码中的in.read()。

下面是j2se文档资料
int java.io.InputStream.read()
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

A subclass must provide an implementation of this method.

Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException if an I/O error occurs.

这句话非常重要
Returns:
the next byte of data, or -1 if the end of the stream is reached.

当没有发送end of the stream 标识的话,那么程序属于等待状态。 也就是java端一直处于读的状态。
解决这个问题的话。 要么终端手动发送eof.要么终端发送每一次交互的字节长。服务器端根据这个字节长来读取相应长度的字节。
西雅图很忙°

2024-05-13 03:32:27

out.println("test_outputs");
后面加个
out.flush();