![](/img/trans.png)
[英]How to read byte[] of variable size from DataInputStream in Java?
[英]Read byte arrays from DataInputStream
我有一個Java中的TCP Client
,可以與C# TCP Server
通信,反之亦然。 它們通過發送byte
數組進行通信。 我在讀取客戶端中的字節數組時遇到問題。 字節數組的固定長度為4。
例如,當服務器發送:
[2,4,0,2]
[2,4,0,0]
客戶端輸出為:
連接端口:10000
剛連接到/192.168.1.101:10000
服務器說[2,4,0,0]
我該如何解決? 似乎第一個數組被覆蓋了嗎?
TCPClient.java
public class TCPClient {
private OutputStream outToServer=null;
private DataOutputStream out=null;
private ByteProtocol byteProtocol;
Socket client;
InputStream inFromServer;
DataInputStream in;
public void initConnection(){
try {
int serverPort = 10000;
InetAddress host = InetAddress.getByName("192.168.1.101");
System.out.println("Connecting to port :" + serverPort);
client = new Socket(host, serverPort);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
outToServer = client.getOutputStream();
out=new DataOutputStream(outToServer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void readBytes(){
try {
inFromServer = client.getInputStream();
in = new DataInputStream(inFromServer);
byte[] buffer = new byte[4];
int read = 0;
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
in.read(buffer);
System.out.println("Server says " + Arrays.toString(buffer));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void sendBytes(byte [] byteArray) throws IOException{
out.write(byteArray);
}
public void closeClient() throws IOException{
client.close();
}
}
您好像兩次讀入緩沖區:
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
in.read(buffer);
因此,在循環頭中讀取的內容將被第二個read()
覆蓋。
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
in.read(buffer);
System.out.println("Server says " + Arrays.toString(buffer));
}
您應該使用DataInputStream.readFully()
而不是此read()
構造,請參閱此相關問題 。 否則,您將無法確定是否已填滿緩沖區。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.