【发布时间】:2014-01-20 07:52:46
【问题描述】:
所以。我有一个 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();
}
[服务器 (PHP)]
function write(&$client, $message)
{
$message = explode("\n", $message);
foreach ($message as $line)
{
socket_write($client['sock'], $line."\0");
}
}
但是当它读取所有字节时,in.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);
}
}
[服务器 (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 我认为关闭流或类似的东西有问题...
-
读取字节后(它们已经在缓冲区中),将它们附加到另一个数组中。我不确定这是否会导致您的问题。
-
@user2310289 我会在 2 小时内试试。