Java基础之网络编程

TCP/IP参考模型

在这里插入图片描述

IP

ip地址:InetAddress

  • 唯一定位一台网络上计算机
  • 127.0.0.1本机localhost
  • ip地址分类
    • ipv4/ipv6
      • ipv4:127.0.0.1 4个字节,0-255
      • ipv6:128位 8个无符号整数
    • 公网(互联网)-私网(局域网)
      • ABCD类地址
      • 192.168.xx.xx专门给组织内部使用的
  • 域名:记忆IP问题
public class TestInetAdress {
	public static void main(String[] args) {
		try {
			//查询本机地址
			InetAddress inetAddress1 =InetAddress.getByName("127.0.0.1");
			System.out.println(inetAddress1);
			InetAddress inetAddress2 =InetAddress.getByName("localhost");
			System.out.println(inetAddress2);
			InetAddress inetAddress3 =InetAddress.getLocalHost();
			System.out.println(inetAddress3);
			
			//查询网站ip地址
			InetAddress inetAddress4 =InetAddress.getByName("www.bai.com");
			System.out.println(inetAddress4);
			//常用方法
			System.out.println(inetAddress4.getCanonicalHostName());//规范的名字
			System.out.println(inetAddress4.getHostAddress());//ip
			System.out.println(inetAddress4.getHostName());//域名或自己电脑的名字
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
/127.0.0.1
localhost/127.0.0.1
DESKTOP-UDIU5JN/192.168.0.102
www.bai.com/45.76.29.156
45.76.29.156
45.76.29.156
www.bai.com

端口

端口表示 计算机上的一个程序的进程

  • 不同进程有不同的端口号!用来区分软件
  • 被规定0-65535
  • TCP,UDP:65535*2 单个协议下端口号不能冲突
  • 端口分类
    • 公有端口0-1023
      • HTTP:80
      • HTTPS:443
      • FTP:21
      • Telent:23
    • 程序注册端口:1024-49151,分配用户或程序
      • Tomcat:8080
      • MySQL:3306
      • Oracle:1521
    • 动态,私有:49152-65535
netstat -ano #查看所有端口
netstat -ano|findstr "5900"#产看指定端口 
tasklist|findstr "8696"#产看指定端口的进程 
public class TestInetSocketAdress {
	public static void main(String[] args) {
		InetSocketAddress socketAddress1 = new InetSocketAddress("127.0.0.1", 8080);
		InetSocketAddress socketAddress2 = new InetSocketAddress("localhost", 8080);
		System.out.println(socketAddress1);
		System.out.println(socketAddress2);
		System.out.println(socketAddress1.getAddress());
		System.out.println(socketAddress1.getHostName());//地址
		System.out.println(socketAddress1.getPort());//端口
	}
}

通信协议

TCP/IP协议簇:实际是一组协议
重要:

  • TCP:用户传输协议
  • UDP:用户数据报协议

出名:

  • TCP:用户传输协议
  • IP:网络互连协议

TCP/UDP对比:
TCP:打电话

  • 连接,稳定
  • 三次握手,四次挥手
三次握手(three-way handshaking)

1.背景:TCP位于传输层,作用是提供可靠的字节流服务,为了准确无误地将数据送达目的地,TCP协议采纳三次握手策略。

2.原理:

1)发送端首先发送一个带有SYN(synchronize)标志地数据包给接收方。

2)接收方接收后,回传一个带有SYN/ACK标志的数据包传递确认信息,表示我收到了。

3)最后,发送方再回传一个带有ACK标志的数据包,代表我知道了,表示’握手‘结束。

通俗的说法

1)Client:嘿,李四,是我,听到了吗?

2)Server:我听到了,你能听到我的吗?

3)Client:好的,我们互相都能听到对方的话,我们的通信可以开始了。


在这里插入图片描述

四次挥手(Four-Way-Wavehand)

1.意义:当被动方收到主动方的FIN报文通知时,它仅仅表示主动方没有数据再发送给被动方了。
但未必被动方所有的数据都完整的发送给了主动方,所以被动方不会马上关闭SOCKET。
它可能还需要发送一些数据给主动方后,再发送FIN报文给主动方,告诉主动方同意关闭连接,所以这里的ACK报文和FIN报文多数情况下都是分开发送的。

2.原理:

 1)第一次挥手:Client发送一个FIN,用来关闭Client到Server的数据传送,Client进入FIN_WAIT_1状态。

 2)第二次挥手:Server收到FIN后,发送一个ACK给Client,确认序号为收到序号+1(与SYN相同,一个FIN占用一个序号),Server进入CLOSE_WAIT状态。

 3)第三次挥手:Server发送一个FIN,用来关闭Server到Client的数据传送,Server进入LAST_ACK状态。

 4)第四次挥手:Client收到FIN后,Client进入TIME_WAIT状态,接着发送一个ACK给Server,确认序号为收到序号+1,Server进入CLOSED状态,完成四次挥手

通俗的说法

1)Client:我所有东西都说完了

2)Server:我已经全部听到了,但是等等我,我还没说完

3)Server:好了,我已经说完了

4)Client:好的,那我们的通信结束l


在这里插入图片描述

  • 客户端,服务端
  • 传输完成,释放连接,效率低

UDP:发短信

  • 不连接,不稳定
  • 客户端,服务端:没有明确的界限
  • 不管有没有准备好,都可以发给你

TCP聊天

//服务端
public class TestServerDemo1 {
	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream is =null;
		ByteArrayOutputStream baos =null;
		try {
			//1.建立服务端口
			serverSocket = new ServerSocket(9999);
			while(true) {
				//2.等待客户端连接过来
				socket = serverSocket.accept();
				//3.读取客户端消息
				is = socket.getInputStream();
				//管道流
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len;
				while ((len = is.read(buffer))!=-1) {
					baos.write(buffer, 0, len);
				}
				System.out.println(baos.toString());
			}
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {//先开后关,捕获异常
			if(baos!=null) {
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(is!=null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(serverSocket!=null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

//客户端
public class TestClientDemo1 {
	public static void main(String[] args) {
		Socket socket = null;
		OutputStream os = null;
		try {
			//1.要知道服务器的地址,端口号
			InetAddress serverIP =InetAddress.getByName("127.0.0.1");
			int port =9999;
			//2.创建一个Socket连接
			socket = new Socket(serverIP, port);
			//3.发送消息 IO流
			os =socket.getOutputStream();
			os.write("hello".getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {//先开后关,捕获异常
			if(os!=null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	}
}

TCP文件上传
IDEA成功,Ecplise失败。。。

//服务端
public class TcpServerDemo1 {
	public static void main(String[] args) throws Exception {
		//1.创建服务
		ServerSocket serverSocket = new ServerSocket(8080);
		//2.监听客户端的连接
		Socket socket =serverSocket.accept();
		//3.获取输入流
		InputStream is =socket.getInputStream();
		//4.文件输出
		FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
		byte[] buffer = new byte[1024];
		int len;
		while ((len=is.read(buffer))!=-1) {
			fos.write(buffer,0,len);
		}
		//通知客户端我接收完了
//		OutputStream os =socket.getOutputStream();
//		os.write("接收完毕,你可以断开了".getBytes());
		//关闭资源
//		os.close();
		fos.close();
		is.close();
		socket.close();
		serverSocket.close();
		
		
	}
}

//客户端
public class TcpClientDemo1 {
	public static void main(String[] args) throws Exception {
		//1.创建一个Socket连接
		Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8080);
		//2.创建一个输出流
		OutputStream os =socket.getOutputStream();
		//3.读取文件
		FileInputStream fis = new FileInputStream(new File("lufei.jpg"));
		//4.写出文件
		byte[] buffer = new byte[1024];
		int len;
		while ((len= fis.read(buffer))!=-1) {
			os.write(buffer,0,len);
		}
		//通知服务器,我已经结束了
//		socket.shutdownOutput();
		//确定服务器接收完毕,才能断开连接
//		InputStream inputStream =socket.getInputStream();
//		
//		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		byte[] buffer2 = new byte[1024];
//		int len2;
//		while ((len2= fis.read(buffer2))!=-1) {
//			baos.write(buffer2, 0, len2);
//		}
//		System.out.println(baos.toString());
		//关闭文件
//		baos.close();
//		inputStream.close();
		fis.close();
		os.close();
		socket.close();

	
	}
}

UDP消息发送

//不需要连接服务器
public class UdpClientDemo1 {
    public static void main(String[] args) throws Exception {
        //1.建立一个Socket
        DatagramSocket socket = new DatagramSocket();
        //2.建个包
        String msg = "你好啊";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port =8080;
        //数据,数据长度起始,要发给谁
        DatagramPacket packet =new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
        //3.发送包
        socket.send(packet);
        //4.关闭流
        socket.close();
    }
}
//还是要等到(客户端)的连接
public class UdpServerDemo1 {
    public static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket socket = new DatagramSocket(8080);
        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
        socket.receive(packet);//阻塞接收
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        //关闭连接
        socket.close();
    }
}

UDP多线程聊天

public class TalkSend implements Runnable{
    DatagramSocket socket =null;
    BufferedReader reader =null;
    private  int fromPort;
    private  String toIP;
    private  int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(fromPort);
            //准备数据,控制台读取
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                String data = reader.readLine();
                byte[] datas =data.getBytes();
                DatagramPacket packet =new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
                //发送包
                socket.send(packet);
                if (data.equals("bye")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        socket.close();
    }
}
public class TalkReceive implements Runnable{
    DatagramSocket socket =null;
    private  int port;
    private String msgFrom;
    public TalkReceive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom=msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                //准备接收包裹
                byte[] container = new byte[1024];
                DatagramPacket packet =new DatagramPacket(container,0,container.length);
                socket.receive(packet);//阻塞接收
                //断开连接
                byte[] data =packet.getData();
                String receiveData = new String(data,0,data.length);
                System.out.println(msgFrom+": "+receiveData);
                if (receiveData.equals("bye")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
public class TalkStudent {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"老师")).start();
    }
}
public class TalkTeacher {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"学生")).start();
    }
}

URL

统一资源定位符
DNS域名解析:https://www.baidu.com xxx.x…x.x
协议://ip地址:端口/项目名/资源

public class URLDemo {
    public static void main(String[] args) throws MalformedURLException {
         URL url = new URL("https://www.bilibili.com/blackboard/activity-yellowVSgreen5th.html");
        System.out.println(url.getProtocol());//协议
        System.out.println(url.getHost());//主句ip
        System.out.println(url.getPort());//端口
        System.out.println(url.getPath());//文件
        System.out.println(url.getFile());//全路径
        System.out.println(url.getQuery());//参数

    }
}

URL下载资源

public class URLDemo {
    public static void main(String[] args) throws Exception {
        //1.下载地址
        URL url = new URL("https://s2.music.126.net/style/web2/img/sprite.png?1a1a0e0219c531c6d1d7900c6f44bb3f");
        //2.连接这个资源
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream =urlConnection.getInputStream();
        FileOutputStream fos =new FileOutputStream("sprite.png");
        byte[] buffer =new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);//写出这个数据
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接
    }
}

学习视频:狂神说Java

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值