所以。我有一个PHP套接字服务器和Java套接字客户端。
也许这是一个愚蠢的问题......但我没有找到答案。
在客户端,我需要从输入流中读取传入字节并将它们放入字节数组中。
我试着这样做:如何从Java中的字节流中读取(PHP/Java套接字通信)
[客户端(JAVA)]
public static byte[] read(BufferedInputStream in)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[32768];
while (true) {
int readBytesCount = in.read(buffer);
if (readBytesCount == -1) {
break;
}
if (readBytesCount > 0) {
baos.write(buffer, 0, readBytesCount);
}
}
baos.flush();
baos.close();
return baos.toByteArray();
}
[SERVER(PHP)
function write(&$client, $message)
{
$message = explode("\n", $message);
foreach ($message as $line)
{
socket_write($client['sock'], $line."\0");
}
}
但是,当它读取的所有字节,在.read()不返回-1,所以循环不停止。 有一次,它返回13(长度),然后 - 没有。 有什么建议吗?
已解决!
[客户端(JAVA)]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[32768];
while (true) {
int readBytesCount = in.read(buffer);
if (getString(buffer).contains("#!EOS!#")) {
baos.flush();
baos.close();
return baos.toByteArray();
}
if (readBytesCount > 0) {
baos.write(buffer, 0, readBytesCount - 1);
}
}
[SERVER(PHP)
function write(&$client, $message)
{
$message = explode("\n", $message);
$message = str_replace("\r", "", $message);
foreach ($message as $line)
{
rLog("Write to ".$client['ip'].": ".$line);
socket_write($client['sock'], $line."\0") or die("[".date('Y-m-d H:i:s')."] Could not write to socket\n");
}
socket_write($client['sock'], "#!EOS!#");
}
@ user2310289我认为有关闭流或类似这样的问题... – RussianVodka
读完字节后(它们已经在缓冲区中),将它们追加到另一个数组中。 我不确定这是否会导致您的问题。 –
@ user2310289我会在2小时内尝试。 – RussianVodka