TCP网络编程

TCP实例一

package com.nbchina.tcp1;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;


public class TcpClinet {


	public static void main(String[] args) throws Exception, IOException {
		Socket s = new Socket("192.168.1.68",10003);
		
		OutputStream out = s.getOutputStream();
		
		out.write("Tcp send data...".getBytes());
		
		s.close();
	}

}



package com.nbchina.tcp1;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端、客户端通讯,服务端守候并显示客户端发来的信息
public class TcpServer {


	public static void main(String[] args) throws IOException {
		//建立服务端socket服务,并监听一个端口
		ServerSocket ss = new ServerSocket(10003);
		//通过accept 方法获取连接来的客户端对象
		Socket s = ss.accept();
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+"...connected");
		
		//获取客户端发来的数据
		InputStream is = s.getInputStream();
		
		byte[] buf = new byte[1024];
		int len = is.read(buf);
		System.out.println(new String(buf,0,len));
		s.close();//关闭客户端。服务端关的不是自己。是客户端。
		ss.close();//关闭服务端
	}

}

TCP实例二

package com.nbchina.tcp2;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


public class TcpClinet {


	public static void main(String[] args) throws Exception {
		Socket s = new Socket("192.168.1.68",10008);
		
		OutputStream out = s.getOutputStream();
		
		out.write("Tcp send data...".getBytes());
		
		InputStream is = s.getInputStream();
		
		byte[] buf = new byte[1024];
		
		int len = is.read(buf);
		
		System.out.println(new String(buf,0,len));
		s.close();
	}

}


package com.nbchina.tcp2;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//客户端、服务端通讯互相发送消息


public class TcpServer {


	public static void main(String[] args) throws Exception {
		//建立服务端socket服务,并监听一个端口
		ServerSocket ss = new ServerSocket(10008);
		//通过accept 方法获取连接来的客户端对象
		Socket s = ss.accept();
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+"...connected");
		
		//获取客户端发来的数据
		InputStream is = s.getInputStream();
		
		byte[] buf = new byte[1024];
		int len = is.read(buf);
		System.out.println(new String(buf,0,len));
		
		OutputStream out = s.getOutputStream();
		
		out.write("收到客户端发来的信息".getBytes());
		s.close();//关闭客户端。服务端关的不是自己。是客户端。
		ss.close();//关闭服务端
	}

}

TCP实例三

package com.nbchina.tcp3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;


public class TcpClinet {


	public static void main(String[] args) throws Exception {
		Socket s = new Socket("192.168.1.2",10008);
		BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
		
		//BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
		
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		
		String line = null;
		
		while((line=bufr.readLine())!=null){
			
			if("over".equals(line)){
				break;				
			}
			out.println(line);
/*			bufOut.write(line);
			bufOut.newLine();
			bufOut.flush();*/
			
			String str = bufIn.readLine();
			System.out.println("server:"+str);
		}
		bufr.close();
		s.close();
	}

}



package com.nbchina.tcp3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
//客户端、服务端通讯互相发送消息

/*
 * 要求建立一个文本转换服务端
 * 客户端发给服务端文本,服务端将文本转换为大写返回给客户端。
 * 而且客户端可以不断的进行文本转换,当客户端输入over时,转换结束。
 * 分析:
 * 客户端:
 * 既然是操作设备上的数据,可以用io技术,并按照io的操作规则来思考。
 * 源:键盘录入
 * 目的:网络设备,网络输出流。
 * 而且操作的是文本数据,可以选择字符流。
 * 
 * 步骤
 * 1、建立服务
 * 2、获取键盘录入
 * 3、将数据发给服务端
 * 4、服务端返回大写数据
 * 5、结束、关闭资源
 * 
 * 都是文本数据,可以使用字符流进行操作,同时提高效率,加入缓冲。
 * 
 */

public class TcpServer {


	public static void main(String[] args) throws Exception {
		//建立服务端socket服务,并监听一个端口
		ServerSocket ss = new ServerSocket(10008);
		//通过accept 方法获取连接来的客户端对象
		Socket s = ss.accept();
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+"...connected");
		
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
		
		//BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		
		//既可以接受字节流又可以接受字符流
		//PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		
		String line = null;
		
		while((line=bufIn.readLine())!=null){
			out.println(line.toUpperCase());
/*			bufOut.write(line.toUpperCase());
			bufOut.newLine();
			bufOut.flush();*/
		}
		s.close();//关闭客户端。服务端关的不是自己。是客户端。
		ss.close();//关闭服务端
	}

}


TCP实例四

package com.nbchina.tcp4;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

//通过tcp复制文本文件。
//注意使用流结束标志。
//一般使用流结束标志。也可以自定义标志。

public class TcpClinet {


	public static void main(String[] args) throws Exception {
		Socket s = new Socket("192.168.1.2",10008);
		BufferedReader bufr = new BufferedReader(new FileReader("IPDeom.java"));

		
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
/*		DataOutputStream dos = new DataOutputStream(s.getOutputStream());
		long time = System.currentTimeMillis();
		dos.writeLong(time);*/
		
		String line = null;
		
		while((line=bufr.readLine())!=null){
		
			out.println(line);

		}
		s.shutdownOutput();//一般使用关闭客户端输出流,相当于给流加入一个结束标记 
		//dos.writeLong(time);//使用时间戳作为结束标志
		//out.println("over");//输出结束,供服务端判断。否则双方都在等待
		
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
		
		String str = bufIn.readLine();
		System.out.println("server:"+str);
		
		bufr.close();
		s.close();
	}

}


package com.nbchina.tcp4;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

//(TCP复制文件)
/*
 * 
 */

public class TcpServer {


	public static void main(String[] args) throws Exception {
		//建立服务端socket服务,并监听一个端口
		ServerSocket ss = new ServerSocket(10008);
		//通过accept 方法获取连接来的客户端对象
		Socket s = ss.accept();
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+"...connected");
		
		DataInputStream dis = new DataInputStream(s.getInputStream());
		long l = dis.readLong();
		
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));

		PrintWriter out = new PrintWriter(new FileWriter("server.txt"),true);
		
		String line = null;
		
		while((line=bufIn.readLine())!=null){
			/*if("over".equals(line))
				break;*/

			out.println(line);
		}
		PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
		pw.println("上传成功");
		out.close();
		s.close();//关闭客户端。服务端关的不是自己。是客户端。
		ss.close();//关闭服务端
	}

}


TCP实例五

package com.nbchina.tcp5;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//通过tcp复制图片文件。

public class TcpClinet {


	public static void main(String[] args) throws Exception {
		Socket s = new Socket("192.168.1.2",10008);
		FileInputStream fis = new FileInputStream("1.bmp");
		OutputStream out = s.getOutputStream();
		byte[] buf = new byte[1024];
		
		
		int len = 0;
		
		while((len=fis.read(buf))!=-1){
		
			out.write(buf,0,len);

		}
		s.shutdownOutput();
		InputStream in = s.getInputStream();
		byte[] bufIn = new byte[1024];
		int num = in.read(bufIn);
		System.out.println(new String(bufIn,0,num));
		
		
		fis.close();
		s.close();
	}

}


package com.nbchina.tcp5;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


/*
 * 单人上传图片
 */

public class TcpServer {


	public static void main(String[] args) throws Exception {
		//建立服务端socket服务,并监听一个端口
		ServerSocket ss = new ServerSocket(10008);
		//通过accept 方法获取连接来的客户端对象
		Socket s = ss.accept();
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+"...connected");
		
		InputStream in = s.getInputStream();
		FileOutputStream fos = new FileOutputStream("server.bmp");
		
		byte[] buf = new byte[1024];
		int len = 0;
		while((len=in.read(buf))!=-1){
		
			fos.write(buf,0,len);

		}
		
		OutputStream out = s.getOutputStream();
		out.write("上传成功".getBytes());
		fos.close();
		s.close();//关闭客户端。服务端关的不是自己。是客户端。
		ss.close();//关闭服务端
	}

}

TCP实例六

package com.nbchina.tcp6;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//通过tcp复制图片文件。

public class TcpClinet {


	public static void main(String[] args) throws Exception {
		if(args.length!=1){
			System.out.println("请选择一个jpg格式的图片");
			return;
		}
		
		File file = new File(args[0]);
		if(!(file.exists()&&file.isFile())){
			System.out.println("该文件有问题,不存在或者不是文件");
			return;
		}
		if(!file.getName().endsWith(".jpg")){
			System.out.println("格式错误");
			return;
		}
			
		if(file.length()>1024*1024*5){
			System.out.println("文件过大");
			return;
		}
			
		
		Socket s = new Socket("192.168.1.2",10008);
		FileInputStream fis = new FileInputStream(file);
		OutputStream out = s.getOutputStream();
		byte[] buf = new byte[1024];
		
		
		int len = 0;
		
		while((len=fis.read(buf))!=-1){
		
			out.write(buf,0,len);

		}
		s.shutdownOutput();
		InputStream in = s.getInputStream();
		byte[] bufIn = new byte[1024];
		int num = in.read(bufIn);
		System.out.println(new String(bufIn,0,num));
		
		
		fis.close();
		s.close();
	}

}


package com.nbchina.tcp6;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


/*
 * 并发上传图片
 */
class PicTread implements Runnable{
	private Socket s;
	PicTread(Socket s){
		this.s=s;
	}
	public void run(){
		int count=1;
		String ip= s.getInetAddress().getHostAddress();
		try{
			System.out.println(ip+"...connected");
			InputStream in = s.getInputStream();
			File file = new File(ip+"("+(count)+")"+".jpg");
			while(file.exists()){
				file = new File(ip+"("+(count)+")"+".jpg");
			}
			FileOutputStream fos = new FileOutputStream(file);
			
			byte[] buf = new byte[1024];
			int len = 0;
			while((len=in.read(buf))!=-1){
			
				fos.write(buf,0,len);

			}
			
			OutputStream out = s.getOutputStream();
			out.write((ip+"上传成功").getBytes());
			fos.close();
			s.close();//关闭客户端。服务端关的不是自己。是客户端。		
		}catch(Exception e){
			throw new RuntimeException(ip+"上传失败");
		}
	}
}
public class TcpServer {


	public static void main(String[] args) throws Exception {
		//建立服务端socket服务,并监听一个端口
		ServerSocket ss = new ServerSocket(10008);
		while(true){
			Socket s = ss.accept();
			new Thread(new PicTread(s)).start();
		}
		

		//ss.close();//关闭服务端
	}

}

TCP实例七

package com.nbchina.tcp7;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

//通过tcp登录

public class TcpClinet {


	public static void main(String[] args) throws Exception {

		
		Socket s = new Socket("192.168.1.2",10008);
		BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
		
		for(int x = 0;x < 3;x++){
			String line = bufr.readLine();
			if(line==null)
				break;
			out.println(line);
			String info = bufIn.readLine();
			System.out.println("info:"+info);
			if(info.contains("欢迎")){
				break;
			}
		}

		bufr.close();
		s.close();
	}

}



package com.nbchina.tcp7;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


/*
 * 
 */
class UserTread implements Runnable{
	private Socket s;
	UserTread(Socket s){
		this.s=s;
	}
	public void run(){
		String ip= s.getInetAddress().getHostAddress();
		System.out.println(ip+"...connected");
		try{
			for(int x=0;x<3;x++){
				BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
				String name = bufIn.readLine();
				if(name==null){
					break;
				}
				BufferedReader bufr = new BufferedReader(new FileReader("user.txt"));
				PrintWriter out = new PrintWriter(s.getOutputStream(),true);
				String line = null;
				
				boolean flag = false;
				while((line = bufr.readLine())!=null){
					if(line.equals(name)){
						flag = true;
						break;
					}
				}
				
				if(flag){
					System.out.println(name+"已经登录");
					out.println(name+"欢迎光临");
					break;
				}else{
					System.out.println(name+"尝试登录");
					out.println(name+"不存在");
				}
			
			}
			s.close();//关闭客户端。服务端关的不是自己。是客户端。		
		}catch(Exception e){
			throw new RuntimeException(ip+"登录失败");
		}
	}
}
public class TcpServer {


	public static void main(String[] args) throws Exception {
		//建立服务端socket服务,并监听一个端口
		ServerSocket ss = new ServerSocket(10008);
		while(true){
			Socket s = ss.accept();
			new Thread(new UserTread(s)).start();
		}
		

		//ss.close();//关闭服务端
	}

}

TCP实例八 ---->服务消息转换

package com.nbchina.tcp.client;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.nbchina.tcp.server.Server;


/**
 * 此类模拟客户端发出更新请求,在运行期间会要求用户输入指令码
 * 举例:输入FDFCF802AAAAAAAAAAAAAAAAAAAAAAAA0000X,详细查看《端口与服务器通讯协议》
 * 此类可以多次运行,从而模拟多个终端 如果输入的指令码错误,服务器将不予解析
 * 
 */
public class Client {
	protected static Logger logger = Logger.getLogger(Server.class.getName());

	static {
		logger.setLevel(Level.ALL); // 查看所有跟踪信息
	}

	public void call() {
		int p = 0;
		DataInputStream in;
		DataOutputStream out;
		Socket socket = null;
		try {
			socket = new Socket(InetAddress.getByName(null), Server.PORT_SERVER);
			/*
			 * 确保一个进程关闭Socket后,即使他还未释放端口,同一个主机的其他进程还可以立即重用该端口,
			 * 可调用socket.setReuseAddress(true),默认false
			 */

			socket.setReuseAddress(true);
			p = socket.getLocalPort(); // 获取本地TCP端口,用于区分不同的客户端
			logger.info("新建客户端连接@" + p);
			in = new DataInputStream(socket.getInputStream());
			out = new DataOutputStream(socket.getOutputStream());

			System.out.print("请输入指令字符串(以回车键结束,以FDFCF8开头):");
			BufferedReader line = new BufferedReader(new InputStreamReader(
					System.in));
			String s = line.readLine();
			// 将字符串转换成字节数组
			for (int ii : s2a(s)) {
				out.write(ii);
			}

			out.flush();
			socket.shutdownOutput(); // 发送指令完毕

			// 接收服务端响应
			StringBuffer sb = new StringBuffer();
			while (true) {
				try {
					int b = in.readUnsignedByte();
					sb.append(Integer.toHexString(b));
				} catch (Exception e) {
					break;
				}
			}

			sb.insert(0, "收到了服务器响应:");
			System.out.println(sb.toString().toUpperCase());

			in.close();
			out.close();
			logger.info("客户端关闭@" + p);
		} catch (IOException e) {
			logger.severe(e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		 new Client().call();

//		int[] b = GportClient.s2a("20EFD23FE");
//		for (int bi : b) {
//			System.out.println(bi);
//		}
	}

	static int[] s2a(String s) {
		if (s == null || "".equals(s)) return new int[0];
		StringBuffer sb = new StringBuffer(s);
		int[] ba = new int[sb.length() / 2 + sb.length() % 2];
		int l = sb.length();
		for (int i = 0, c = 0; i < l; i++, c++) {
			String tmp = "" + sb.charAt(i++);
			if (i < l)
				tmp += sb.charAt(i);
			ba[c] = Integer.parseInt(tmp, 16);
		}
		return ba;
	}
}



package com.nbchina.tcp.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.nbchina.tcp.msg.DisconnectMessage;
import com.nbchina.tcp.msg.Message;

/**
 * 守护的通信服务器,可以启动和关闭<br>
 * 启动后,服务器运行一个守护线程负责接收终端更新请求,并分配给解析器解析编码 提供通用的socket发送和接收功能
 * 
 */
public class Server extends ServerSocket {
	protected static Logger logger = Logger.getLogger(Server.class.getName());

	static {
		logger.setLevel(Level.ALL);       // 查看所有跟踪信息
	}
	
	public static final int PORT_SERVER = 10000;
	
	public static final int MSG_MAX_LENGTH = 1024;
	
	
	private static Server server;

	public static Server newInstant() {
		if (server == null) {
			try {
				server = new Server();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return server;
	}
	
	private Server() throws IOException {
		super(PORT_SERVER);
	}

	public void start() {
		try {
			while (true) {
				Socket socket = this.accept();
				logger.info("建立新会话");
				//new Instant(socket).start();  Instant extends Thread修改为 Instant implements Runnable
				new Thread(new Instant(socket)).start();
			}
		} catch (Exception e) {
			logger.severe("服务器启动或接收数据失败:" + e.getMessage());
		} finally {
			try {
				logger.info("关闭服务器");
				super.close();
			} catch (IOException e) {
				logger.severe("服务器关闭失败:" + e.getMessage());
			}
		}
	}

	/**
	 * 一个服务器实例,根据目前设计,一个终端的一次会话对应一个实例
	 * 单例模式,懒汉
	 */
	public static class Instant implements Runnable {
		private Socket socket;

		public Instant(Socket socket) {
			this.socket = socket;
		}

		public Socket getSocket() {
			return socket;
		}
		
		public void run() {
			logger.info("成功创建一个连接,等待客户端数据");
			
			Message reponse;
			try {
				reponse = new Receiver(socket).process();
				logger.info("数据处理完成,发送响应");
				
				Sender sender = new Sender(socket);
				if (reponse != null) {
					sender.send(reponse);
				}
				
				// 总在最后发送关闭消息
				Message close = new DisconnectMessage();
				sender.send(close);
				
				logger.info("连接处理完成并关闭");
			} catch (Exception e) {
				InetAddress ad = socket.getInetAddress();
				logger.warning("消息处理发生错误:" + e.getMessage() + "@" + ad.getCanonicalHostName());
			} finally {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		logger.info("开始启动服务器");
		Server.newInstant().start();
	}
}



package com.nbchina.tcp.server;
import java.net.Socket;
import java.util.logging.Logger;

import com.nbchina.tcp.dao.StubDao;
import com.nbchina.tcp.msg.Message;
import com.nbchina.tcp.msg.ResponseMessage;
import com.nbchina.tcp.msg.UpdateMessage;


/**
 * 接收并解析编码
 * 
 */
public class Receiver {
	protected static Logger logger = Logger.getLogger(Receiver.class.getName());

	private Socket socket;

	private StubDao dao;

	public Receiver(Socket socket) {
		this.socket = socket;

		this.dao = new StubDao();
	}

	public Message process() throws Exception {
		UpdateMessage request = new UpdateMessage(socket.getInputStream());

		// 判断是否是处理过的终端
		String id = request.getId();
		if (!dao.hasRegister(id)) {
			// 未处理过的,先注册(注册完以后,也应该查询是否有更新,可能是服务端已经录入了终端的注册信息)
			dao.register(id);
		}

		Message reponse = null;
		if (dao.isUpdated(id)) {
			// 是处理过的,查询更新信息
			reponse = new ResponseMessage(dao.fillMessageDetail(id));
		}

		return reponse;
	}
}



package com.nbchina.tcp.server;

import java.io.DataOutputStream;
import java.net.Socket;
import java.util.logging.Logger;

import com.nbchina.tcp.msg.Message;

/**
 * 负责发送消息
 */
public class Sender {
	protected static Logger logger = Logger.getLogger(Sender.class.getName());

	private Socket socket;

	public Sender(Socket socket) {
		this.socket = socket;
	}

	public void send(Message msg) throws Exception {
		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
		int[] data = msg.getData();
		for (int d : data) {
			dos.write(d);
		}

		dos.flush();
	}
}

.....还有其他一些类

网络获取图片、html

public class HtmlRequest {
	public static void main(String[] args) throws Exception {
		URL url = new URL("http://www.sohu.com/");
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5 * 1000);
		InputStream inStream = conn.getInputStream();//通过输入流获取html数据
		byte[] data = readInputStream(inStream);//得到html的二进制数据
		String html = new String(data,"utf-8");
		
		System.out.println(html);
		
/*		File imageFile = new File("nbchina.htm");
		FileOutputStream outStream = new FileOutputStream(imageFile);
		outStream.write(data);
		outStream.close();*/
		
	}

	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}



public class ImageRequest {
	public static void main(String[] args) throws Exception {
		URL url = new URL("http://img04.taobaocdn.com/bao/uploaded/i4/T1hTSvXihAXXbeLMw1_041248.jpg_b.jpg");
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5 * 1000);
		InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
		byte[] data = readInputStream(inStream);//得到图片的二进制数据
		File imageFile = new File("nbchina.jpg");
		FileOutputStream outStream = new FileOutputStream(imageFile);
		outStream.write(data);
		outStream.close();
	}

	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}

多线程下载

public class MulThreadDownload {

	public static void main(String[] args) {
		String path = "http://dl_dir.qq.com/qqfile/qq/QQ2011/QQ2011.exe";
		try {
			new MulThreadDownload().download(path, 5);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 从路径中获取文件名称
	 * @param path 下载路径
	 * @return
	 */
	public static String getFilename(String path){
		return path.substring(path.lastIndexOf('/')+1);
	}
	/**
	 * 下载文件
	 * @param path 下载路径
	 * @param threadsize 线程数
	 */
	public void download(String path, int threadsize) throws Exception{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5 * 1000);
		int filelength = conn.getContentLength();//获取要下载的文件的长度
		String filename = getFilename(path);//从路径中获取文件名称
		File saveFile = new File(filename);
		RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
		accessFile.setLength(filelength);//设置本地文件的长度和下载文件相同
		accessFile.close();
		//计算每条线程下载的数据长度
		int block = filelength%threadsize==0? filelength/threadsize : filelength/threadsize+1;
		for(int threadid=0 ; threadid < threadsize ; threadid++){
			new DownloadThread(url, saveFile, block, threadid).start();
		}
	}
	
	private final class DownloadThread extends Thread{
		private URL url;
		private File saveFile;
		private int block;//每条线程下载的数据长度
		private int threadid;//线程id

		public DownloadThread(URL url, File saveFile, int block, int threadid) {
			this.url = url;
			this.saveFile = saveFile;
			this.block = block;
			this.threadid = threadid;
		}

		@Override
		public void run() {
			//计算开始位置公式:线程id*每条线程下载的数据长度= ?
		    //计算结束位置公式:(线程id +1)*每条线程下载的数据长度-1 =?
			int startposition = threadid * block;
			int endposition = (threadid + 1 ) * block - 1;
			try {
				RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
				accessFile.seek(startposition);//设置从什么位置开始写入数据
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5 * 1000);
				conn.setRequestProperty("Range", "bytes="+ startposition+ "-"+ endposition);
				InputStream inStream = conn.getInputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while( (len=inStream.read(buffer)) != -1 ){
					accessFile.write(buffer, 0, len);
					System.out.println("线程id:"+ threadid+ "下载["+len+"]");
				}
				inStream.close();
				accessFile.close();
				System.out.println("线程id:"+ threadid+ "下载完成");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值