1. 程式人生 > >java-TCP協議發送和接收數據

java-TCP協議發送和接收數據

amr throws while user class get client put println

服務器:

public class FileServerDemo {

public static void main(String[] args) throws IOException {
//創建服務器對象
ServerSocket ss = new ServerSocket(8080);
//監聽
Socket s = ss.accept();
//包裝通道內的輸入流
BufferedInputStream bis = new BufferedInputStream(
s.getInputStream());
//把數據寫入文件
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("C:\\Users\\MA\\Desktop\\IOtest\\copy.jpg"));
byte[] bys = new byte[1024];
int len = 0;
while((len = bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//把通道內的輸出流包裝
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
write.write("文件上傳成功");
write.newLine();
write.flush();
//釋放資源
bos.close();
s.close();
ss.close();
}
}

客戶端:

public class FileClientDemo {

public static void main(String[] args) throws IOException {
//創建客戶端對象
Socket s = new Socket("172.24.60.182",8080);
//讀取文件的數據
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\MA\\Desktop\\電路指導書\\QQ圖片20180627212519.jpg"));
//把通道內的輸出流包裝
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
byte[] bys = new byte[1024];
int len = 0;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//給服務器一個反饋
s.shutdownOutput();//禁用輸出流
//獲取服務器的反饋信息
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String data = reader.readLine();
System.out.println("client:"+data);
bis.close();
s.close();
}
}

java-TCP協議發送和接收數據