TCP文件上传实现

tech2026-08-04  0

TCP文件上传实现

客户端

public class TestClientDemo03 { public static void main(String[] args) { Socket socket = null; OutputStream outputStream = null; FileInputStream fileInputStream = null; try { //1.获得服务端的IP地址 InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); //2.获得服务端的Port端口号 int port = 8989; //3.创建与服务端的连接 socket = new Socket(inetAddress,port); //4.给服务端发送数据信息 outputStream = socket.getOutputStream(); //5.读取文件 fileInputStream = new FileInputStream(new File("FJ.jpg")); //6.写出文件 byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1){ outputStream.write(buffer,0,len); } }catch (Exception e){ e.printStackTrace(); }finally { if (null != fileInputStream){ try { fileInputStream.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != outputStream){ try { outputStream.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != socket){ try { socket.close(); }catch (IOException e){ e.printStackTrace(); } } } } }

服务端

public class TestServerDemo03 { public static void main(String[] args) throws Exception{ ServerSocket serverSocket = null; Socket socket = null; InputStream inputStream = null; FileOutputStream fileOutputStream = null; try { //1.创建一个服务端IP地址 serverSocket = new ServerSocket(8989); while (true){ //2.接收客户端套接字 socket = serverSocket.accept(); //3.创建读取数据信息的管道 inputStream = socket.getInputStream(); fileOutputStream = new FileOutputStream(new File("receive1.jpg")); //4.读取客户端发送的数据信息 byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1){ fileOutputStream.write(buffer,0,len); } } }catch (Exception e){ e.printStackTrace(); }finally { if (null != fileOutputStream){ try { fileOutputStream.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != inputStream){ try { inputStream.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != socket){ try { socket.close(); }catch (IOException e){ e.printStackTrace(); } } if (null != serverSocket){ try { serverSocket.close(); }catch (IOException e){ e.printStackTrace(); } } } } }
最新回复(0)