使用Socket和ServerSocket上传文件

来源:互联网 发布:origin画图软件注册 编辑:程序博客网 时间:2024/05/17 23:50
public class UploadClient {public static void main(String[] args) throws IOException {String path="D:\\1.jpg";Socket socket=new Socket("192.168.1.102",9888);BufferedInputStream bi=new BufferedInputStream(new FileInputStream(path));OutputStream os=socket.getOutputStream();byte[] b=new byte[1024];int length=0;while((length=bi.read(b))>0){os.write(b, 0, length);}socket.shutdownOutput();System.out.println("$$$$$$$$$$$$$$$$$$");InputStream is=socket.getInputStream();byte[] bs=new byte[1024];int len=is.read(bs);String returndata=new String(bs,0,len);System.out.println("服务端返回的信息:"+returndata);bi.close();os.close();is.close();}}
public class UploadServer {public static void main(String[] args) throws IOException {ServerSocket server=new ServerSocket(9888);Socket socket=server.accept();InputStream is=socket.getInputStream();BufferedInputStream bi=new BufferedInputStream(is);BufferedOutputStream bo=new BufferedOutputStream(new FileOutputStream("D:\\1copy.jpg"));byte[] bs=new byte[1024];int len=0;while((len=bi.read(bs))>0){bo.write(bs, 0, len);System.out.println(len);}OutputStream os=socket.getOutputStream();os.write("上传成功".getBytes());bi.close();os.close();bo.close();is.close();}}