使用TCP協議將使用者傳送的資訊接收並儲存
阿新 • • 發佈:2020-12-20
使用TCP協議將使用者傳送的資訊接收並儲存
客戶端:
Socket socket = null;
try {
socket = new Socket(InetAddress.getByName("10.17.128.82"), 12439);
OutputStream outputStream = socket.getOutputStream();
Scanner sc= new Scanner(System.in);
String str = sc.nextLine();//獲取鍵盤輸入
byte [] buf = str.getBytes();
outputStream.write(buf);//傳送要儲存的資料
System.out.println("資料已經發送");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
socket.close();//關閉資源
} catch (IOException e) {
e.printStackTrace();
}
}
}
服務端:
while(true) {
ServerSocket serverSocket = null;
FileOutputStream fileOutputStream = null;
File file = new File("src\\file\\paper.txt");
byte buf[] = new byte[1024];
try {
serverSocket = new ServerSocket(12439);
Socket accept = serverSocket.accept();
InputStream inputStream = accept. getInputStream();//獲取輸入流
inputStream.read(buf);//讀取資料,資料在buf陣列中
serverSocket.close();//關閉資源
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(buf);
System.out.println("接收到的資料已經寫入txt檔案中");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
結果: