学习JavaEE的日子 Day38 网络编程

发布于:2024-04-15 ⋅ 阅读:(133) ⋅ 点赞:(0)

Day38 网络编程(了解即可)

1. 计算机网络

在这里插入图片描述

2. 网络编程

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

3. 网络模型

两台计算机之间的通信是根据什么规则来走的(OSI & TCP/IP)

在这里插入图片描述

此处简单了解该模型就行《TCP/IP详解》《TCP协议簇》

4. 网络编程三要素

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

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

在这里插入图片描述

4.1. IP地址

理解:网络中计算机的唯一标识(IP地址是一个32位的二进制数据)

注意:127.0.0.1表示本机地址

4.2. 端口号

理解:应用程序在电脑上的唯一标识

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

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

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

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

4.3. 网络协议

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

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

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

HTTP…

5. InetAddress类

理解:用来表示主机的信息

注意:一个域名 对应 多个IP地址

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

6. Socket

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

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

7. TCP编程

理解:客户端(发送一个请求),服务端(接收到这个请求,给予响应)

API:Socket,ServerSocket

7.1. 简单的TCP通信

在这里插入图片描述

编写服务端程序

//服务端
public class Server {

	public static void main(String[] args) throws IOException {
		
		//大堂经理
		ServerSocket server = new ServerSocket(8080);
		
		//18号技师
		//注意:accept()是线程阻塞的方法,该方法会等待客户端的连接成功后才生成一个Socket对象与之交互
		Socket socket = server.accept();
		
		//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("18号技师:今年18岁");
		
		br.close();
		ps.close();
		server.close();
	}
}

编写客户端程序

//客户端
public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		//注意:关闭流相当于关闭Socket!!!
		
		//巴得伟
		Socket socket = new Socket("127.0.0.1", 8080);
		
		//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();
		
		
	}
}

注意:先运行服务程序,再运行客户端程序

7.2 TCP案例

7.2.1 传输文件

服务端

public class Server {
	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(8080);//端口号要对应
		
		Socket socket = server.accept();
		
		BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.mp4"));
		
		byte[] bs = new byte[1024];
		int len;
		while((len = bis.read(bs)) != -1){
			bos.write(bs, 0, len);
		}
		
		bis.close();
		bos.close();
		server.close();
	}
}

客户端

public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1", 8080);
		
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("视频.mp4"));
		BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
		
		byte[] bs = new byte[1024];
		int len;
		while((len = bis.read(bs)) != -1){
			bos.write(bs, 0, len);
		}
		
		bis.close();
		bos.close();
		socket.close();
	}
}
7.2.2 单聊
public class Server {
	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(8080);
		
		Socket socket = server.accept();
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while(true){
			ps.println("18号技师:" + scan.next());
		}
		
	}
}
public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1", 8080);
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while(true){
			ps.println("巴得伟:" + scan.next());
		}
		
	}
}

接收消息的多线程

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 (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}		
		
	}
}
7.2.3 群聊

在这里插入图片描述

public class Server {
	
	public static final ConcurrentHashMap<String, PrintStream> map = new ConcurrentHashMap<>();

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(8080);
		
		while(true){
			
			Socket socket = server.accept();
			
			String ip = socket.getInetAddress().toString();
			PrintStream ps = new PrintStream(socket.getOutputStream());
			map.put(ip, ps);
			
			new ServerThread(socket).start();
		}
		
	}
}
public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1", 8080);
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while(true){
			ps.println("巴得伟:" + scan.next());
		}
		
	}
}
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 (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
}
public class ServerThread extends Thread{
	
	private Socket socket;
	
	public ServerThread(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);
				
				//发送给其他客户端消息
				Set<Entry<String,PrintStream>> entrySet = Server.map.entrySet();
				for (Entry<String, PrintStream> entry : entrySet) {
					String ip = entry.getKey();
					PrintStream ps = entry.getValue();
					
					if(!socket.etInetAddress().toString().equals(ip)){
						ps.println(readLine);
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}				
		
	}
}

8.TCP三次握手 和 四次挥手

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

9. UDP编程

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

UDP — 发短信

TCP — 打电话

9.1 简单的UDP通信

注意:

1.UDP协议的Socket是DatagramSocket

2.7070表示的是自己的端口号,不是对方的端口号

public class Client01 {
	public static void main(String[] args) throws IOException {

		DatagramSocket socket = new DatagramSocket(7070);
		
		//1.向客户端2发送数据
		byte[] buf = "用良心做教育".getBytes();
		DatagramPacket p = new DatagramPacket(buf , 0, buf.length, InetAddress.getByName("127.0.0.1"), 8080);
		socket.send(p);
		
		//4.接受来自客户端1的数据
		buf = new byte[1024];
		p = new DatagramPacket(buf , buf.length);
		socket.receive(p);
		System.out.println(new String(buf).trim());
		
		socket.close();
	}
}
public class Client02 {
	public static void main(String[] args) throws IOException {
		
		DatagramSocket socket = new DatagramSocket(8080);
		
		//2.接受来自客户端1的数据
		byte[] buf = new byte[1024];
		DatagramPacket p = new DatagramPacket(buf , buf.length);
		socket.receive(p);
		System.out.println(new String(buf).trim());
		
		//3.向客户端2发送数据
		buf = "做真实的自己".getBytes();
		p = new DatagramPacket(buf , 0, buf.length, InetAddress.getByName("127.0.0.1"), 7070);
		socket.send(p);
		
		socket.close();
	}
}

9.2 UDP案例 之 单聊

public class Client01 {
	public static void main(String[] args) throws SocketException {
		
		DatagramSocket socket = new DatagramSocket(7070);
		
		new ReceiveThread(socket).start();
		new SendThread("巴得伟", "127.0.0.1", 8080, socket).start();
	}
}
public class Client02 {
	public static void main(String[] args) throws SocketException {
		
		DatagramSocket socket = new DatagramSocket(8080);
		
		new ReceiveThread(socket).start();
		new SendThread("王益升", "127.0.0.1", 7070, socket).start();
	}
}
public class ReceiveThread extends Thread{
	
	private DatagramSocket socket;
	
	public ReceiveThread(DatagramSocket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		while(true){
			byte[] buf = new byte[1024];
			DatagramPacket p = new DatagramPacket(buf , buf.length);
			try {
				socket.receive(p);
				System.out.println(new String(buf).trim());
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
}
public class SendThread extends Thread{
	
	private String nickName;
	private String ip;
	private int port;
	private DatagramSocket socket;
	
	public SendThread(String nickName, String ip, int port, DatagramSocket socket) {
		this.nickName = nickName;
		this.ip = ip;
		this.port = port;
		this.socket = socket;
	}
	
	@Override
	public void run() {
		Scanner scan = new Scanner(System.in);
		while(true){
			byte[] buf = (nickName + ":" + scan.next()).getBytes();
			try {
				DatagramPacket p = new DatagramPacket(buf, buf.length, InetAddress.getByName(ip), port);
				socket.send(p);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

9.3 TCP VS UDP

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

10.HTTP

请求–resquest

响应–response

10.1 需求:获取淘宝商品周边类别

public class Test01 {
	public static void main(String[] args) throws IOException {
		
		String path = "https://suggest.taobao.com/sug?code=utf-8&q=%E8%80%90%E5%85%8B&callback=cb";
		
		//创建链接对象
		URL url = new URL(path);
		//获取连接对象
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		
		//设置参数
		connection.setConnectTimeout(5000);//设置连接超时时间
		connection.setReadTimeout(5000);//设置读取数据超时时间
		connection.setDoInput(true);//设置是否允许使用输入流
		connection.setDoOutput(true);//设置是否允许使用输出流
		
		//获取响应状态码
		int code = connection.getResponseCode();
		if(code == HttpURLConnection.HTTP_OK){
			
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			char[] cs = new char[1024];
			int len;
			while((len = br.read(cs)) != -1){
				System.out.println(new String(cs, 0, len));
			}
			
			
		}else if(code == HttpURLConnection.HTTP_NOT_FOUND){
			System.out.println("页面未找到");
		}				
		
	}
}

10.2 需求:下载图片

public class Test02 {
	public static void main(String[] args) throws IOException {
		
		String path = "https://wx2.sinaimg.cn/mw690/e2438f6cly1hoo3qpm7vrj21111jk4mn.jpg";
		
		//创建链接对象
		URL url = new URL(path);
		//获取连接对象
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		
		//设置参数
		connection.setConnectTimeout(5000);//设置连接超时时间
		connection.setReadTimeout(5000);//设置读取数据超时时间
		connection.setDoInput(true);//设置是否允许使用输入流
		connection.setDoOutput(true);//设置是否允许使用输出流
		
		//获取响应状态码
		int code = connection.getResponseCode();
		if(code == HttpURLConnection.HTTP_OK){
			
			BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("金智媛.jpg"));
			byte[] bs = new byte[1024];
			int len;
			while((len = bis.read(bs)) != -1){
				bos.write(bs, 0, len);
			}
			
			bis.close();
			bos.close();
			
		}else if(code == HttpURLConnection.HTTP_NOT_FOUND){
			System.out.println("页面未找到");
		}				
		
	}
}

网站公告

今日签到

点亮在社区的每一天
去签到