简体   繁体   English

JAVA中的I / O-从java.net.Socket读取数据

[英]I/O in JAVA - reading data from java.net.Socket

I have a problem with my client - server apps which I developed in JAVA. 我的客户端有问题-我用JAVA开发的服务器应用程序。 I use Socket and ServerSocket from java.net* package. 我使用java.net*包中的SocketServerSocket When client connect to the server, client sends message for example 7200 bytes. 当客户端连接到服务器时,客户端发送消息,例如7200字节。 In server I use InputStream . 在服务器中,我使用InputStream Sometimes I receive whole message (7200 bytes), but many times I receive less than 7200 bytes. 有时我收到整个消息(7200字节),但是很多时候我收到的消息少于7200字节。 Is there any way in JAVA to receive whole message and close connection? JAVA中有什么方法可以接收整个消息并关闭连接? Maybe should I use other library to tcp/ip connection in JAVA? 也许我应该在JAVA中使用其他库进行tcp / ip连接?

Probably this will help: InputStream.read() documentation. 可能会有所帮助: InputStream.read()文档。

Reads some number of bytes from the input stream and stores them into the buffer array b. 读取从输入流一定数量的字节,并将其存储到缓冲数组b。 The number of bytes actually read is returned as an integer. 实际读取的字节数以整数形式返回。

This method will not block until the entire byte buffer filled up or stream end reached. 直到整个字节缓冲区填满或流结束,该方法才会阻塞。 Instead, it returns as much data as available at the moment. 相反,它会返回当前可用的尽可能多的数据。

This is not likely to happen when reading from files, but quite normal for sockets. 从文件读取时,这不太可能发生,但是对于套接字来说,这是很正常的。

The actual number of bytes, which were written into byte-buffer is returned, so you can you that to decide if there's enough data. 返回已写入字节缓冲区的实际字节数,因此您可以确定是否有足够的数据。

You can use read(buf, start, len), to start not from beginning of buffer but continue data block. 您可以使用read(buf,start,len)来从缓冲区的开头而不是从数据块的开头开始。 For example, if you are reading exactly 7200 bytes, do: 例如,如果你正在读正好 7200字节,这样做:

byte [] buf = new byte[7200];
int len = 7200;
int pos=0;

while(len > 0) {
  int rd = is.read(buf, pos, len);
  if(rd<0) {
      //premature EOF
      break;
  }
  pos += rd;
  len -= rd;
}

Otherwise if you do not know message length up front you have several options. 否则,如果您不预先知道消息的长度,则可以选择几种方法。 Among them: 其中:

  1. Send message length as first 4 bytes, then always read 4 bytes first, then allocate buffer of necesary size and read into it 发送消息长度为前4个字节,然后始终先读取4个字节,然后分配必要大小的缓冲区并读入其中
  2. Read into buffer until you receive "END-OF-MESSAGE" marker. 读入缓冲区,直到收到“ END-OF-MESSAGE”标记。 Like, for example "END-OF-LINE". 例如“ END-OF-LINE”。 When you find it - stop reading and process message. 找到它后-停止阅读并处理消息。

我建议从jboss到tcpip通信使用jgroups( http://www.jgroups.org/manual/html/index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM