[英]How to read multiple types of data from socket on java
我寫了一些文件傳輸應用程序。 在客戶端和服務器之間,我發送 3 種類型的數據:
1) 一些“命令詞”,例如 READY_FOR_UPLOAD。
2)一些可序列化的數據
3)字節數組中的大文件。
我在服務器套接字上獲得客戶端連接並為每個客戶端創建新線程。
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
InputStream inputStream = clientSocket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {}
我使用資源嘗試創建這些流,沒有問題。
我用:
1) "in" 用於從客戶端讀取消息:
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
2)“out”用於發送消息。
3)“inputStream”接收文件:
try (FileOutputStream fileOutputStream = new
FileOutputStream("D:\\testDownload.zip");
BufferedOutputStream bufferedOutputStream = new
BufferedOutputStream(fileOutputStream)
) {
byte[] buffer = new byte[1024 * 100];
int read;
while ((read = inputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, read);
}
}
4) 可序列化數據的“objectInputStream”:
Object object;
if ((object = objectInputStream.readObject()) != null) {
if (object instanceof File) {
File file = (File) object;
System.out.println(file.getAbsolutePath());
System.out.println(file.length());
}
}
雖然我單獨使用它們 - 沒有問題。 但我首先需要閱讀“命令詞”,即在我的踏板方法運行的開始。
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
InputStream inputStream = clientSocket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
String line;
if ((line = in.readLine()) != null) {
System.out.println(line);
there i should try to read other types of data
}
}
如果這不是“命令字”,我可以嘗試讀取可序列化數據或文件數據。 但這是一個問題,我可能會嘗試讀取一行,但它可以是文件數據的可序列化數據的一部分,並且因為 inputsream 讀取“一對一”字節方法,我不能嘗試像可序列化或文件數據那樣讀取它,因為輸入不再完整。 我在“readLine()”中讀取了一些數據。 在嘗試讀取數據之前,我應該知道我收到的數據類型? 怎么做到呢?
您需要創建一個協議 - 規則客戶端和服務器如何在它們之間交換信息。 當您寫入數據時,您指定要發送的數據類型及其大小。 並且不要在 Socket 上使用 ObjectInputStream 和 ObjectOutputStream - 將數據轉換為字節數組,以便在寫入時知道大小,然后再將它們轉換回來。 以字節形式發送數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.