网络编程及三大协议(TCP + UDP + Http)

网络编程及三大协议(TCP + UDP + Http)

一、网络编程

1.计算机网络

是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。

2.网络编程

实现多台计算机之间实现数据的共享和传递,网络应用程序主要组成为:
网络编程+IO流+多线程

3.网络编程三要素

网络通讯的模型:请求-响应,客户端-服务端

三要素:IP地址,端口,协议(数据传输的规则)

1.IP地址

1.1.IP地址:网络中计算机的唯一标识(IP地址是一个32位的二进制数据,为了方便,将一个字节的二进制转换为一个十进制的数据)

1.2.IP地址的组成:网络号段+主机段

1.3.1.A类IP地址:第一段号码为网络号码,剩下的三段号码为本地计算机的号码
----可以配置256256256台主机

1.3.2.B类IP地址:前二段号码为网络号码,剩下的二段号码为本地计算机的号码
C类IP地址:前三段号码为网络号码,剩下的一段号码为本地计算机的号码

补充:
A类地址的表示范围为:0.0.0.0~126.255.255.255,默认网络屏蔽为:255.0.0.0;A类地址分配给规模特别大的网络使用。A类网络用第一组数字表示网络本身的地址,后面三组数字作为连接于网络上的主机的地址。分配给具有大量主机(直接个人用户)而局域网络个数较少的大型网络。例如IBM公司的网络。

B类地址的表示范围为:128.0.0.0~191.255.255.255,默认网络屏蔽为:255.255.0.0;

C类地址的表示范围为:192.0.0.0~223.255.255.255,默认网络屏蔽为:255.255.255.0;C类地址分配给小型网络,如一般的局域网和校园网,它可连接的主机数量是最少的,采用把所属的用户分为若干的网段进行管理。

2.端口号

正在运行的程序的标识

  1. A:每个网络程序都会至少有一个逻辑端口

  2. B:用于标识进程的逻辑地址,不同进程的标识不同

  3. C:有效端口:065535,其中01024系统使用或保留端口。

a) 80

b) ftp:23

c) www.baidu.com:80

  1. 通过第三方工具可以查看

注意:端口与协议有关:TCP和UDP的端口互不相干,同一个协议的端口不能重复,不同协议的可以重复

TCP:10086

UDP:10086

3.协议

通信规则,就是数据的传输规则

TCP、UDP都是传输层的协议

TCP建立连接,形成传输数据的通道;在连接中进行大数据量传输;通过三次握手完成连接,是可靠协议;必须建立连接,效率会稍低,例如:打电话

UDP将数据源和目的封装到数据包中,不需要建立连接;每个数据报的大小在限制在64k;因无连接,是不可靠协议;不需要建立连接,速度快:例如发短信

4.InetAddress – 主机类

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Test01 {

	public static void main(String[] args) throws UnknownHostException {
		
		//获取到指定域名的服务器IP地址
//		InetAddress byName = InetAddress.getByName("www.baidu.com");
//  	System.out.println(byName);//14.215.177.39
	
		//获取到指定域名的所有服务器 IPd地址
//		InetAddress[] allByName = InetAddress.getAllByName("www.baidu.com");
//		for (InetAddress inetAddress : allByName) {
//			System.out.println(inetAddress);
//		}
		
		//获取到本机的IP地址
		InetAddress localHost = InetAddress.getLocalHost();
		System.out.println(localHost);
	}
}

二、TCP协议

Scoket也叫套接字,其表示的是IP地址和端口号的组合。

网络编程主要就是指Socket编程,网络间的通信其实就是Socket间的通信,数据就通过IO流在两个Scoket间进行传递。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class Client {
	//注意:关闭流等于关闭Socket
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		//武松
		Socket socket = new Socket("127.0.0.001", 8888);
		
		//1.向服务端发送消息
		PrintStream ps = new PrintStream(socket.getOutputStream());
		ps.println("武松:小二,上好酒好菜!");
		
		//4.接收来自服务端的消息
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
		String readLine = br.readLine();
		System.out.println(readLine);
		
		//关闭资源
		ps.close();
		br.close();
		socket.close();
	}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class Server {

	public static void main(String[] args) throws IOException {
		
		//客栈掌柜
		ServerSocket server = new ServerSocket(8888);
		
		System.out.println("等待端连接中...");
		
	
		//店小二
		//accept()是线程阻塞的方法,客户端和服务端连接成功后才会生成一个Socket对象
		Socket socket = server.accept();
		
		System.out.println("欢迎光临,客人来了~~~");
		
		//2.接收来自客户端的消息
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
		String readLine = br.readLine();
		System.out.println(readLine);
		
		//3.向客户端发送消息
		PrintStream ps = new PrintStream(socket.getOutputStream());
		ps.println("店小二:好的,您请坐!");
		
		//关闭资源
		br.close();
		ps.close();
		socket.close();
		server.close();
	}
}

1.TCP案例之 传输文件

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

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.002", 6666);
		
		//客户端读取源文件,通过Socket提供的输出流向服务端传输数据即可
		
		FileInputStream fis = new FileInputStream("测试视频.mp4");
		OutputStream os = socket.getOutputStream();
		
		byte[] b = new byte[1024];
		int len;
		while ((len = fis.read(b)) != -1) {
			os.write(b, 0, len);
		}
		fis.close();
		os.close();
		socket.close();
	}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(6666);
		Socket socket = server.accept();
		
		//通过Socket提供过的输入流接收来自客户端的数据,并写入到本地文件中
		InputStream is = socket.getInputStream();
		FileOutputStream fos = new FileOutputStream("copy.mp4");
		
		byte[] b = new byte[1024];
		int len;
		while ((len = is.read(b)) != -1) {
			fos.write(b, 0, len);
		}
		
		is.close();
		fos.close();
		socket.close();
		server.close();
	}
}

2.TCP协议 之 一对一聊天

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.001", 5555);
		
		Scanner scan = new Scanner(System.in);
		
		PrintStream ps = new PrintStream(socket.getOutputStream());
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
		
		while (true) {
			
			ps.println("小小:" + scan.next());
			
			String readLine = br.readLine();
			System.out.println(readLine);
		}
		
	}
}

3.TCP协议 之 优化一对一聊天

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1",5010);
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		
		while (true) {
			ps.println("刘备:" + scan.next());
		}
	}
}
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(5010);
		
		Socket socket = server.accept();
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		
		while (true) {
			ps.println("张飞:" + scan.next());
		}
	}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ReceiveThread extends Thread{

	private Socket socket;

	public ReceiveThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
			while (true) {
				String readLine = br.readLine();
				System.out.println(readLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

4.TCP协议 之 群聊

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1", 4563);
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while (true) {
			ps.println("关羽:" + scan.next());
		}
	}
}

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

public class Server {

	public static final ConcurrentHashMap<String, Socket> map = new ConcurrentHashMap<>();
	
	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(4563);
		
		while (true) {
			
			Socket socket = server.accept();
			
			//获取客户端的IP地址
			String ip = socket.getInetAddress().toString();
			System.out.println(ip);
			
			//将IP地址和Socket对象存入Map中
			map.put(ip,socket);
			
			//此线程 -- 接收当前Socket的消息,并发送给其他Socket
			 new ServerThread(socket).start();
		}
	}
}

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

public class ReceiveThread extends Thread{

	private  Socket socket;

	public ReceiveThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {

		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
			while (true) {
				String readLine = br.readLine();
				System.out.println(readLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ServerThread extends Thread{

	private Socket socket;

	public ServerThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		//接收当前Socket的消息,并发送给其他Socket
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
			
			while (true) {
				String readLine = br.readLine();
				System.out.println(readLine);
				
				ConcurrentHashMap<String, Socket> map = Server.map;
				Set<Entry<String,Socket>> entrySet = map.entrySet();
				for (Entry<String, Socket> entry : entrySet) {
					String ip = entry.getKey();
					Socket value = entry.getValue();
					
					if (!socket.getInetAddress().toString().equals(ip)) {
						PrintStream ps = new PrintStream(value.getOutputStream());
						ps.println(readLine);
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

四、UDP协议

1.简介

UDP(User Datagram Protocol)用户数据报包协议,UDP和TCP位于同一层-传输层,但它对于数据包的顺序错误或重发没有TCP可靠;UDP是一种面向无连接的通信协议。UDP向应用程序提供一种发送封装的原始IP数据报的方法,并且发送时无需建立连接,不保证可靠数据的传输

UDP — 发短信

TCP — 打电话

import java.net.DatagramSocket;
import java.net.SocketException;

public class Client01 {

	public static void main(String[] args) throws SocketException {
		
		DatagramSocket socket = new DatagramSocket(8808);
		
		new ReceiveThread(socket).start();
		
		new SendThread(socket, "127.0.0.1", 9099, "马超").start();
		
	}
}

import java.net.DatagramSocket;
import java.net.SocketException;

public class Client02 {

	public static void main(String[] args) throws SocketException {
		
		DatagramSocket socket = new DatagramSocket(9099);
		
		new ReceiveThread(socket).start();
		new SendThread(socket, "127.0.0.1", 8808, "吕布").start();
	}
}

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ReceiveThread extends Thread{

	private DatagramSocket socket;

	public ReceiveThread(DatagramSocket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {

		while (true) {
		
			try {
				//数据容器
				byte[] buf = new byte[1024];
				//数据报包
				DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
				//接收数据报包
				socket.receive(dp);
				//打印
				System.out.println(new String(buf).trim());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class SendThread extends Thread{

	private DatagramSocket socket;
    private String ip;
    private int port;
    private String name;
    
    public SendThread(DatagramSocket socket, String ip, int port, String name) {
		this.socket = socket;
		this.ip = ip;
		this.port = port;
		this.name = name;
	}

	@Override
    public void run() {
		
		Scanner scan = new Scanner(System.in);
		
		while (true) {
			
			try {
				//数据
				byte[] buf = (name + ":" + scan.next()).getBytes();
				//数据报包
				DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
				//发送数据报包
				socket.send(dp);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
}

2.TCP VS UDP

TCP UDP
是否连接 面向连接 无面向连接
传输可靠性 可靠 不可靠
应用场合 传输大量数据 少量数据
速度

五、Http协议

1.Http案例之获取来电归属地

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class Test01 {

	public static void main(String[] args) throws IOException {
		
		//获取链接地址
		URL url = new URL("https://cx.shouji.360.cn/phonearea.php?number=15879090133");
		//获取连接对象
		HttpsURLConnection huc = (HttpsURLConnection) url.openConnection();
		
		//设置参数
		//设置请求方式
		huc.setRequestMethod("GET");
		//允许使用输入流
		huc.setDoInput(true);
		//允许使用输出流
		huc.setDoOutput(true);
		//设置连接超时时间
		huc.setConnectTimeout(5000);
		//设置读取超时时间
		huc.setReadTimeout(5200);
		
		//获取响应状态码
		int responseCode = huc.getResponseCode();
		
		if (responseCode == HttpsURLConnection.HTTP_OK) {//响应成功
			
			InputStreamReader isr = new InputStreamReader(huc.getInputStream(), "UTF-8");
			char[] c = new char[1024];
			int len;
			while ((len = isr.read(c)) != -1) {
				System.out.println(new String(c, 0, len));
			}
			isr.close();
		}else if(responseCode == HttpsURLConnection.HTTP_NOT_FOUND){
			System.out.println("报错了 --- 页面未找到");
		}
	}
}


2.Http案例之获取快递

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class test02 {

	public static void main(String[] args) throws IOException {
		
		//获取地址
		URL url = new URL("https://www.kuaidi100.com/?type=zhongtong&postid=78624759493002");
		
		//获取连接对象
		HttpsURLConnection huc = (HttpsURLConnection) url.openConnection();
		
		//设置参数
		//设置请求方式
		huc.setRequestMethod("GET");
		//允许使用输入流
		huc.setDoInput(true);
		//允许使用输出流
		huc.setDoOutput(true);
		//设置连接超时时间
		huc.setConnectTimeout(5200);
		//设置读取超时时间
		huc.setReadTimeout(5000);
		
		//获取响应状态码
		int responseCode = huc.getResponseCode();
		
		if (responseCode == HttpsURLConnection.HTTP_OK) {//响应成功
			
			InputStreamReader isr = new InputStreamReader(huc.getInputStream(),"UTF-8");
			
			char[] c = new char[1024];
			int len;
			while ((len = isr.read(c)) != -1) {
				System.out.println(new String(c, 0, len));
			}
			isr.close();
		} else if(responseCode == HttpsURLConnection.HTTP_NOT_FOUND){
			System.out.println("报错了 --- 页面未找到");
		}
	}
}

3.Http案例之下载图片

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class Test03 {

	public static void main(String[] args) throws IOException {
		
		//获取连接地址
		URL url = new URL("https://ts1.cn.mm.bing.net/th/id/R-C.f27d775447d9f4ab7c71bbe5f8e38831?rik=4ISLL%2fsQWoSY8g&riu=http%3a%2f%2fimg95.699pic.com%2fphoto%2f40014%2f9369.jpg_wh860.jpg&ehk=S%2bDyu%2bhUKhk%2foLxQ6D7fO350Z%2fkmlDrRz5sM5J1QrCk%3d&risl=&pid=ImgRaw&r=0");
		
		//获取连接对象
		HttpsURLConnection huc = (HttpsURLConnection) url.openConnection();
		
		//设置参数
		//设置请求方式
		huc.setRequestMethod("GET");
		//允许使用输入流
		huc.setDoInput(true);
		//允许使用输出流
		huc.setDoOutput(true);
		//设置连接超时时间
		huc.setConnectTimeout(5200);
		//设置读取超时时间
		huc.setReadTimeout(5000);
		
		
		//获取响应状态码
		int responseCode = huc.getResponseCode();
		
		if (responseCode == HttpsURLConnection.HTTP_OK) {
			
			InputStream is = huc.getInputStream();
			FileOutputStream fos = new FileOutputStream("冲击的力量.jpg");
			
			byte[] b = new byte[1024];
			int len;
			while ((len = is.read(b)) != -1) {
				fos.write(b, 0, len);
			}
			is.close();
			fos.close();
		}else if (responseCode == HttpsURLConnection.HTTP_NOT_FOUND) {
			System.out.println("报错了 --- 页面未找到");
		}
		
	}
}

你可能感兴趣的:(Java基础,java,青少年编程,开发语言,c4java,经验分享)