头都大了!请问怎么得到Socket通信中收到的信息的长度?

seekjob 2002-01-30 12:11:28
头都大了!请问怎么得到Socket通信中收到的信息的长度?

我用Socket通信时,用DataItputsteam接收数据时,我是这样接收的:
用in.avilable()来获得长度;但是我怎么获得都是0。
以致后面我不知道该readbyte()多少个。

另外如果我传输的信息是字符而不是二进制,应该用什么比较好?
我用BufferedInputReader时,ServerSocket程序就停在in.readLine()处了,而我的ClientSocket已经out.write("adfadf".getBytes());out.flush();了。

请高手指点。万分感谢!!
...全文
196 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dump 2002-03-18
  • 打赏
  • 举报
回复
由于socket是阻塞的,所以你只能用线程去读。当然socket是双工的,所以你不用担心读阻塞时是否还可以写。
既然用了线程,就无所谓一次能读多少了,只要一直读到你满意为止,然后处理已读到的数据。
hahaha88 2002-01-31
  • 打赏
  • 举报
回复
下面是 doc of java.io.DataInputStream:
public final int read(byte[] b)
public final int read(byte[] b, int off, int len)
[...]
Returns:
the total number of bytes read into the buffer, or -1 if there is no more
data because the end of the stream has been reached.
[...]

所以你可以用 "return value" 来得到 "real bytes you read", 如果这个值是-1,
你可以跳出循环:
final int myMAX=10000;
byte receive []= new byte [myMAX ];
int counter=0, iTMP=0;
while (isLive) //isLive(boolean) is controlled by other Thread, it
//is better a volatile field, and when other
//Thread changes its value, "syncronized" should
//be used to make the changing of isLive "visible"
//to this Thread
{
iTMP=in.read(receive, counter, myMAX-counter);
if(iTMP==-1) break;
counter += iTMP;
}
oldcat0076 2002-01-30
  • 打赏
  • 举报
回复
你先定义一个相对大一点的byte数组,然后用in.read(byte[])获得长度
skyyoung 2002-01-30
  • 打赏
  • 举报
回复
socket 流是BLOCKING的。
skyyoung 2002-01-30
  • 打赏
  • 举报
回复
input stream without blocking
skyyoung 2002-01-30
  • 打赏
  • 举报
回复
available
public int available()
throws IOException
Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream. The next caller might be the same thread or or another thread.
The available method for class InputStream always returns 0.

This method should be overridden by subclasses.


Returns:
the number of bytes that can be read from this input stream without blocking.
Throws:
IOException - if an I/O error occurs.
肖尧19 2002-01-30
  • 打赏
  • 举报
回复
#
gzgangster 2002-01-30
  • 打赏
  • 举报
回复
DataInputStream din = new DataInputStream(new InputStream());
byte[] content;
int contentLength = din.read(content);
gzgangster 2002-01-30
  • 打赏
  • 举报
回复
DataInputStream din = new DataInputStream(new InputStream());
byte[] content;
int contentLength = din.read(content);

23,407

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧