Java复习之知识点整理(十七)--- TCP、UDP、IP、HTTP、七层协议、端口、套接字、URL、多线程下载URL资源

37 篇文章 3 订阅
一、TCP
-------------------------------------------------------
1.传输控制协议(Transfer Control Protocal)
2.协议:规则,一套规范的数据格式
3.面向连接的,安全,有确认,数据有序(区别于UDP-无连接,不安全,速度快)
4.一般分为三个阶段:建立连接,数据传输,释放连接
5.TCP建立连接的三次握手:实质上是2次身份认证。认证双方


二、IP
-------------------------------------------------------
1.网络协议:Internet Protocal
2.通配ip地址:0:0:0:0
3.InetAddress只有ip没有端口,必须绑定端口
4.InetSocketAddress:相当于InetAddress + port



三、osi开放系统互连参考模型/网络传输的七层协议
------------------------------------------------------
1.物理层 //网线,水晶头;rj45
2.数据链路层 //FDDI
3.网络层 //IP
4.传输层 //TCP UDP
5.会话层 //RPC 远程调用系统
6.表示层 //是否加密
7.应用层 //HTTPS HTTP FTP SMTP(简单邮件协议)


四、http超文本传输协议/FTP文件传输协议
-----------------------------------------------------
1.应用层协议



五、端口
-----------------------------------------------------
1.0-1023:系统端口
2.1024 - 65535: 可用端口
3.查看端口占用情况:cmd + netstat -ano
4.外界访问我,必须通过我的ip访问,但是仅仅直到ip是找不到我的,因为有端口的存在。所以,需要在ip上绑定指定的端口,开启端口监听,这样就能通过ip + 端口找到我了
5.但是一旦开启一个端口,就不能再开启这个端口了,因为被占用了
六、套接字 socket
-----------------------------------------------------
1.socket = ip + tcp/udp + port


@Test
	/**
	 * 测试服务器端Socket
	 * @throws Exception
	 */
	public void tsServerSocket() throws Exception
	{
		//创建InetSocketAddress
		byte [] bs = new byte[]{(byte)192,(byte)168,0,(byte)107};
		InetAddress addr = InetAddress.getByAddress(bs);		
		InetSocketAddress addr1 = new InetSocketAddress(addr, 8888);
		
		//创建ServerSocket
		ServerSocket ss = new ServerSocket();
		
		//绑定InetSocketAddress
		ss.bind(addr1);
		
		//接受请求(阻塞,直到有人发来请求,但是一旦有人连接了,它就退出了,所以一般是死循环)
		while(true)
		{
			Socket s = ss.accept();	
			
			InputStream is = s.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "gbk");
			char [] buf = new char[1024];
			int len = 0;
			while((len = isr.read(buf)) != -1)
			{
				System.out.println(new String(buf,0,len));
			}
			
			InetSocketAddress s1 = (InetSocketAddress)s.getLocalSocketAddress();
			InetSocketAddress s2 = (InetSocketAddress)s.getRemoteSocketAddress();
			System.out.println("local:" + s1.getHostName() + ":" + s1.getPort());
			System.out.println("remote:" + s2.getHostName() + ":" + s2.getPort());
			//System.out.println(s.toString());
		}
		//System.out.println("over");
	}
	
	
	
	/**
	 * 测试客户端套接字
	 */
	@Test
	public void tsClientSocket() throws Exception
	{
		//Socket s = new Socket("localhost", 8888);
		//创建客户端套接字,并连接服务器端
		Socket s = new Socket("192.168.0.107", 8888);
		//得到套接字输出流
		InputStream is = System.in;
		InputStreamReader isr = new InputStreamReader(is, "gbk");
		//BufferedInputStream bis = new BufferedInputStream(is);
		char [] cbuf = new char[1024];
		int len = 0;
		while((len = isr.read(cbuf)) != -1)
		{
			OutputStream os = s.getOutputStream();
			os.write(new String(cbuf,0,len).getBytes("gbk"));
			os.flush();
		}
		
		
		
		while(true)
		{
			Thread.sleep(50000);
		}
		
		//System.out.println("connected!");
	}
	




七、服务器--客户端互发消息案例
---------------------------------------------------------------------------------------------------------

(-------------------服务器端--------------------)

public class Server {
	
	@Test
	/**
	 * 测试服务器端Socket
	 * @throws Exception
	 */
	public void startServer() throws Exception
	{
		//创建InetSocketAddress
		byte [] bs = new byte[]{(byte)192,(byte)168,0,(byte)107};
		InetAddress addr = InetAddress.getByAddress(bs);		
		InetSocketAddress addr1 = new InetSocketAddress(addr, 8888);
		
		//创建ServerSocket
		ServerSocket ss = new ServerSocket();
		
		//绑定InetSocketAddress
		ss.bind(addr1);
		
		
		while(true)
		{
			//接受请求(阻塞,直到有人发来请求,但是一旦有人连接了,它就不阻塞了)
			Socket s = ss.accept();				
			new CommunicationThread(s).start();		
		}
	}
	
	
}

(-------------------通信线程----------------)

/**
 *	通信线程
 */
public class CommunicationThread extends Thread
{
	private Socket s;
	private String clientInfo;
	
	
	public Socket getS() {
		return s;
	}



	public void setS(Socket s) {
		this.s = s;
	}



	public CommunicationThread(Socket s) 
	{
		super();
		this.s = s;
		this.clientInfo = getClientInfo(s);
	}



	public void run()
	{		
		try {
			//接收数据(获取客户端传递过来的数据)
			InputStream is = s.getInputStream();
			//发送数据(给客户端发送数据)
			OutputStream os = s.getOutputStream();
			
			InputStreamReader isr = new InputStreamReader(is);
			char [] buf = new char[1024];
			int len = 0;
			while((len = isr.read(buf)) != -1)
			{
				String msg = new String(buf,0,len);
				System.out.println("[" + clientInfo + "] " + msg);
				os.write(("[from server]" + msg).getBytes());
				os.flush();
			}		
					
		} catch (IOException e) {		
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 获取客户端信息
	 * @return ip + port
	 */
	private String getClientInfo(Socket s)
	{
		//InetSocketAddress s1 = (InetSocketAddress)s.getLocalSocketAddress();
		InetSocketAddress s2 = (InetSocketAddress)s.getRemoteSocketAddress();
		//System.out.println("local:" + s1.getHostName() + ":" + s1.getPort());
		//System.out.println("remote:" + s2.getHostName() + ":" + s2.getPort());
		return "remote:" + s2.getHostName() + ":" + s2.getPort();
	}
}


(-------------------客户端--------------------)
public class Client {


	/**
	 * 测试客户端套接字
	 */
	@Test
	public void startClient() throws Exception
	{
		//创建客户端套接字,并连接服务器端
		Socket s = new Socket("192.168.0.107", 8888);
		OutputStream os = s.getOutputStream();
		//得到套接字输出流
		BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));	
		InputStream is = s.getInputStream();			
		String line = null;
		byte [] buf = new byte [1024];
		int len = 0;
		while((line = bis.readLine()) != null)
		{			
			//这个方法是阻塞的,用户不输入,就一直等待用户输入,一旦输入了,就发给服务器了,执行下面代码
			os.write(line.getBytes()); 
			//接收服务器发送过来的消息,也是阻塞的
			len = is.read(buf);
			System.out.println(new String(buf,0,len));				
		}				
	}	
}



八、windows杀死进程
-------------------------------------------------------
1.taskkill /? //查看帮助
2.taskkill /f /pid 1 //强制杀死进程1
3.taskkill /f /pid 1 /pid 2 //强制杀死进程1和2...
4.taskkill /f /IM notepae.exe /T //强制杀死映像名为notepae.exe的进程树



九、URL
-----------------------------------------------------------
1.统一资源定位符
schema://domainname:port/path?queryString
http://192.168.0.107:9090/a.txt?id=12&&name=tom
http://192.168.0.107:8080
2.HttpURLConnection hcon = (HttpURLConnection)url.openConnection();
hcon.getInputStream();
hcon.getOutputStream();
hcon.getContentLength();
hcon.getContentType();
3.标注写法
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
//设置请求属性
//*****Range bytes=startPos-endPos*****
conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
InputStream is = conn.getInputStream();
...

@Test
	public void testUrl() throws Exception
	{
		//创建url对象
		URL url = new URL("http://192.168.0.107:8080/1.mp3");
		//打开url连接
		HttpURLConnection hcon = (HttpURLConnection)url.openConnection();
		//获取连接流对象
		InputStream is = hcon.getInputStream();
		//OutputStream os = hcon.getOutputStream();
		//hcon.getContentLength();
		
		
		FileOutputStream fos = new FileOutputStream("E:\\a.mp3");
		byte [] buf = new byte[1024];
		int len = 0;
		while((len = is.read(buf)) != -1)
		{
			fos.write(buf,0,len);
		}
		is.close();
		fos.close();
		System.out.println("下载完成!");
	}



十、 URI 统一资源标识符
------------------------------------------------------------


十一、在eclipse中创建tcp/ip监控器
------------------------------------------------------------
1.eclipse -- win --- perfer --- run/debug --- tcp/ip monitor


十二、多线程下载URL服务器资源案例
------------------------------------------------------------------------------

(--------------下载器UI-----------------)

/**
 * 下载器UI
 * @author Administrator
 *
 */
public class DownloaderUI extends JFrame implements ActionListener
{
	private String url;
	private String desPath;
	private int threadCount;
	public JProgressBar pbar;
	private JButton playbtn;
	private JTextArea urltx;
	private JTextArea destx;
	private JTextArea counttx;
	
	
	public static void main(String[] args) {
		//new 窗口
		new DownloaderUI();
	}
	
	public DownloaderUI()
	{
		init();		
	}
	
	/**
	 * 初始化布局
	 */
	private void init()
	{
		//初始化敞口
		this.setBounds(100, 50, 840, 800);
		this.setLayout(null);		
		
		//添加url
		JLabel urllb = new JLabel("URL:");
		urllb.setBounds(10, 10, 800, 50);
		this.add(urllb);
		
		urltx = new JTextArea();
		urltx.setText("http://localhost:8080/1.7z");
		urltx.setBounds(10, 60, 800, 50);
		this.add(urltx);
		
		//添加des
		JLabel deslb = new JLabel("Des:");
		deslb.setBounds(10, 120, 800, 50);
		this.add(deslb);
		
		destx = new JTextArea();
		destx.setText("E:\\1.7z");
		destx.setBounds(10, 170, 800, 50);
		this.add(destx);
		
		//添加count
		JLabel countlb = new JLabel("Count:");
		countlb.setBounds(10, 240, 800, 50);
		this.add(countlb);
		
		counttx = new JTextArea();
		counttx.setText("3");
		counttx.setBounds(10, 290, 800, 50);
		this.add(counttx);
		
		//添加开始按钮
		playbtn = new JButton("开始下载");
		playbtn.setBounds(10, 370, 200, 50);
		playbtn.addActionListener(this);
		this.add(playbtn);
		
		
		//添加进度条
		pbar = new JProgressBar();
		pbar.setBounds(10, 450, 800, 30);
		this.add(pbar);
		
		//添加窗口关闭事件
		this.addWindowListener(new WindowAdapter(){
			
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(-1);
			}				
			
			
		});
			
			
			
			
		this.setVisible(true);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
				
		if(e.getSource() == playbtn)
		{
			System.out.println("开始下载!");
			this.url = urltx.getText();
			this.desPath = destx.getText();			
			this.threadCount = Integer.parseInt(counttx.getText());		
			new DownLoader(url,desPath,threadCount,this).startDownLoad();
		}
	}
	
	
}


(--------------下载器-----------------)
public class DownLoader {

	private String url;
	private String des;
	private int count;
	private DownloaderUI ui;
	private int totleLength;
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getDes() {
		return des;
	}

	public void setDes(String des) {
		this.des = des;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public DownloaderUI getUi() {
		return ui;
	}

	public void setUi(DownloaderUI ui) {
		this.ui = ui;
	}

	public DownLoader(String url, String des, int count, DownloaderUI ui) {
		this.url = url;
		this.des = des;
		this.count = count;
		this.ui = ui;
		this.totleLength = getTotleLength();
		ui.pbar.setMaximum(totleLength);
	}


	/**
	 * 获取源文件总大小
	 * @return
	 */
	private int getTotleLength()
	{
		try {
			
			URL u = new URL(url);
			HttpURLConnection hcon = (HttpURLConnection)u.openConnection();
			return hcon.getContentLength();		
			
		} catch (Exception e) {			
			e.printStackTrace();
		}
		
		return -1;
	}

	
	/**
	 * 开始下载
	 */
	public void startDownLoad() {
			
		int startPos = 0;
		int endPos = 0;
		int blocks = totleLength / count;
				
		for(int i = 0 ; i < count ; i ++)
		{		
			if( i == count - 1)
			{			
				new DownLoadThread(url,des,ui,i * blocks ,totleLength - 1).start();
			}
			new DownLoadThread(url,des,ui,i * blocks,((i + 1) * blocks - 1)).start();
		}		
	}

}

(--------------下载线程-----------------)
public class DownLoadThread extends Thread 
{
	private String url;
	private String des;
	private DownloaderUI ui;
	private int startPos;
	private int endPso;
		
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getDes() {
		return des;
	}

	public void setDes(String des) {
		this.des = des;
	}

	public DownloaderUI getUi() {
		return ui;
	}

	public void setUi(DownloaderUI ui) {
		this.ui = ui;
	}

	public int getStartPos() {
		return startPos;
	}

	public void setStartPos(int startPos) {
		this.startPos = startPos;
	}

	public int getEndPso() {
		return endPso;
	}

	public void setEndPso(int endPso) {
		this.endPso = endPso;
	}

	/**
	 * 创建下载线程
	 * @param url
	 * @param des
	 * @param ui
	 * @param startPos
	 * @param endPso
	 */
	public DownLoadThread(String url, String des, DownloaderUI ui,
			int startPos, int endPso) {
		
		this.url = url;
		this.des = des;
		this.ui = ui;
		this.startPos = startPos;
		this.endPso = endPso;
	}




	public void run()
	{
		//开始下载
		try {
			
			URL u = new URL(url);
			HttpURLConnection http = (HttpURLConnection) u.openConnection();
			//设置请求属性
			//*****Range  bytes=startPos-endPos*****
			http.addRequestProperty("Range", "bytes=" + startPos + "-" + endPso);
			InputStream is = http.getInputStream();
			byte [] buf = new byte[1024];
			int len = 0;
			//定义随机访问流
			RandomAccessFile ras = new RandomAccessFile(des, "rw");
			ras.seek(startPos);
			while((len = is.read(buf)) != -1)
			{
				ras.write(buf,0,len);
				ui.pbar.setValue(ui.pbar.getValue() + len);
			}
			ras.close();
			is.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值