eg:客户端给服务器端传送一张图片
/* 客户端发送文件给服务器端 */ package com.jcwzc01; import com.sun.security.ntlm.Server; import org.junit.Test; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class TestTcp01 { @Test public void client() {//创建客户端测试程序 InetAddress inetAddress; OutputStream outputStream = null; FileInputStream fileInputStream = null; Socket socket = null; { try { inetAddress = InetAddress.getByName("127.0.0.1"); socket = new Socket(inetAddress, 8899); outputStream = socket.getOutputStream();//输出流用于写入文件 fileInputStream = new FileInputStream(new File("G:\\JAVASystem\\xx\\1.jpg"));//文件输入流用于读取文件 byte[] arr = new byte[1024]; int temp; while ((temp = fileInputStream.read(arr)) != -1) { outputStream.write(arr, 0, temp); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } } @Test public void server(){//创建客户端 ServerSocket serverSocket=null; Socket socket=null; InputStream inputStream=null; FileOutputStream fileOutputStream=null; try { serverSocket=new ServerSocket(8899);//指定端口 socket=serverSocket.accept(); inputStream=socket.getInputStream();//输入流用于读取文件 int temp; fileOutputStream=new FileOutputStream(new File("1.jpg"));//文件输出流把客户端发过来的图片保存在文件中 byte[] arr=new byte[1024]; while((temp=inputStream.read(arr))!=-1){ fileOutputStream.write(arr,0,temp); } } catch (IOException e) { e.printStackTrace(); }finally { if(fileOutputStream!=null){ try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(inputStream!=null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket!=null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
注意:先启动服务器程序,在启动客户端程序