java中使用Socket简单实现从服务器下载图片

使用Socket简单实现从服务器下载图片

客户端

public class Client {
	public static void main(String[] args) {
		Socket socket=null;
		try {
			socket=new Socket("192.168.199.215",9999);	//设置ip地址和端口号,建立连接
			InputStream in=socket.getInputStream();	//通过socket获得输入流(从服务器端得到的数据)
			OutputStream out=new FileOutputStream("e:xiazai.jpg");	//创建输出流,设置图片下载后的地址及名字
			BufferedInputStream bufferin=new BufferedInputStream(in);	
			BufferedOutputStream bufferout=new BufferedOutputStream(out);
			int i=0;
			byte[] by=new byte[1024*3];
			while((i=bufferin.read(by))!=-1) {	//边下载边输出
				bufferout.write(by, 0, i);
			}
			bufferout.flush();	//刷新流
			bufferin.close();//关闭
			bufferout.close();
			socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

服务端

public class Server {
	public static void main(String[] args) {
		ServerSocket serverSocket=null;
		try {
			serverSocket=new ServerSocket(9999);	//设置端口号(此端口号要与客户端端口号一致)
			Socket socket=serverSocket.accept();	//接收连接请求
			InputStream in=new FileInputStream("e:123.jpg");	//创建输入流,设置要读取的图片地址;
			OutputStream out=socket.getOutputStream();	//通过ocket得到输出流,向客户端输出;
			BufferedInputStream bufferin=new BufferedInputStream(in);
			BufferedOutputStream bufferout=new BufferedOutputStream(out);
			int i=0;
			byte[] by=new byte[1024*3];
			while((i=bufferin.read(by))!=-1) {	//边读边写
				bufferout.write(by,0,i);
			}
			bufferout.flush();	//刷新
			bufferin.close();	//关闭
			bufferout.close();
			socket.close();
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

你可能感兴趣的:(java基础)