java网络编程的一些基础的知识

1.2网络通信的要素

  1. 通信双方的地址:
  • ip

  • 端口号

    规则:网络通信协议

1.3 IP地址

ip地址:InetAddress

  • 唯一定位一台主机

  • 127.0.0.1 本机localhost

  • ip地址的分类

    • ivp4/ipv6
      • ipv4: 32位
      • ipv6: 128位
    • 公网(互联网)-私网(局域网)
      • ABCD类地址
      • 192.168.XX.XX,专门给组织内部使用(局域网)
  • 域名:记忆IP问题

    package lesson1.com.day1;
    
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    
    //测试IP
    public class TestInetAddress {
    	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);
    			
    			//查询百度地址
    			InetAddress inetAddress5 = InetAddress.getByName("www.baidu.com");
    			System.out.println(inetAddress5);
    			
    			//常用方法
    			System.out.println(inetAddress1.getAddress());	
    			System.out.println(inetAddress1.getCanonicalHostName()); //规范化
    			System.out.println(inetAddress1.getHostAddress()); //ip
    			System.out.println(inetAddress1.getHostName());	//域名,或者自己电脑的名字
    			
    			
    		} catch (UnknownHostException e) {
    			// TODO 自动生成的 catch 块
    			e.printStackTrace();
    		}
    		
    	}
    }
    
    

1.4端口

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

  • 不同的进程有不同的端口号!用来区分软件!

  • 端口分类

    • 共有端口0~1023

      • HTTP :80
      • HTTPS : 443
      • FTP : 21
      • TELENT: 2
    • 程序注册端口:1024~49151,分配用户或者程序

      • Tomcat: 8080
      • MySQL : 3306
      • Oracle :1521
    • 动态,私有 :49152~65535

      netstat -ano  # cmd命令,查看本机的所有端口
      netstat -an0|findstr "5900" # 查看指定端口的进程
      tasklist|findstr "8689" # 查看指定端口的进程
      
      package lesson1.com.p2;
      
      import java.net.InetSocketAddress;
      
      public class TextInetSocketAddress {
      	public static void main(String[] args) {
      		InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080);
      		InetSocketAddress socketAddress1 = new InetSocketAddress("127.0.0.1",8080);
      		System.out.println(socketAddress);
      		System.out.println(socketAddress1);
      		
      		System.out.println(socketAddress.getAddress());
      		System.out.println(socketAddress.getHostName());
      		System.out.println(socketAddress.getPort());
      		System.out.println(socketAddress.getHostString());
      		
      	}
      }
      

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-owUVwzzl-1600247535969)(C:\Users\老司机赖康\AppData\Roaming\Typora\typora-user-images\image-20200915130752029.png)]

1.5通信协议

TCP/IP,UDP

1.6TCP

客户端

  1. 连接服务器
  2. 发送消息
package lesson1.com.p3;

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

public class TextClientDemo01 {
	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流,(先获得一个IO流对象,在向IO中写信息,有中文的话要转成字节流如  .getBytep())
			os = socket.getOutputStream();
			os.write("你好,欢迎学习Java网络编程".getBytes());
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
			if(os != null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
			if(socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}
		
	}
}

服务器端

  1. 建立服务器的端口 ServerSocket
  2. 等待用户的连接accept
  3. 接收用户的消息
package lesson1.com.p3;

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

public class TectServerDemo01 {
	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) {	//先从InputStream中读取数据,在写进ByteArrayOutputStream管道流中
					baos.write(buffer,0,len);
				}
				System.out.println(baos.toString());
			}
			} catch (IOException e) {
				// TODO 自动生成的 catch 
				e.printStackTrace();			
			}finally {
				if(baos !=null) {
					try {
						baos.close();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
				if(is != null) {
					try {
						is.close();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
				if(socket != null) {
					try {
						socket.close();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
				if(serverSocket != null) {
					try {
						serverSocket.close();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
				
			}
	}
}

文件上传

服务器端:

package lesson1.com.p4;

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

public class TextServerDemo02 {
	public static void main(String[] args) throws IOException {
		//1.创建服务
		ServerSocket serverSocket = new ServerSocket(9000);
		//2.监听用户的连接
		Socket socket = serverSocket.accept();
//		Scanner input = new Scanner(System.in);
//		input.hasNext();
		//3.获取输入流
		InputStream is = socket.getInputStream();
		
		//4.获取文件流,输出文件
		FileOutputStream fos = new FileOutputStream(new File("1.text"));
		byte[] buffer = new byte[1024];
		int len;
		while((len = is.read(buffer))!= -1) {	//先从InputStream中读取数据,在写进ByteArrayOutputStream管道流中
			fos.write(buffer,0,len);
		}
		
		//通知客户端我接收完毕了
		OutputStream os = socket.getOutputStream();
		os.write("我接收完毕!".getBytes());
		
		
		//5.关闭资源
		fos.close();
		is.close();
		socket.close();
		serverSocket.close();
	}
}

客户端

package lesson1.com.p4;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TextClientDemo02 {
	public static void main(String[] args) throws Exception{
		//1.创建一个socket连接
		Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
		//2.创建一个输出流
		OutputStream os = socket.getOutputStream();
		
		//3.读取文件
		FileInputStream fis = new FileInputStream(new File("1.txt"));		
	
		//4.写文件
		byte[] buffer = new byte[1024];
		int len;
		while((len = fis.read(buffer))!= -1) {	//先从InputStream中读取数据,在写进ByteArrayOutputStream管道流中
			os.write(buffer,0,len);
		}
		
		//通知服务器,我已经结束了
		socket.shutdownOutput();
		
		//确定服务器接收完毕
		InputStream is = socket.getInputStream(); 
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer1 = new byte[2048];
		int len1;
		while((len1 = is.read(buffer1))!= -1) {	//先从InputStream中读取数据,在写进ByteArrayOutputStream管道流中
			baos.write(buffer,0,len);
		}
		System.out.println(baos.toString());
		
		
		//5.关闭文件
		fis.close();
		os.close();
		socket.close();
		
	}
}

Tomcat

服务器

  • 自定义s
  • Tomcat

客户端

  • 自定义
  • 浏览器B

1.7 UDP

不用连接,需要知道服务器的地址

发送消息

发送端

package lesson1.com.p5;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

//不需要服务器
public class UdpClientDemo01 {
	public static void main(String[] args) throws Exception {
		//1.建立一个Socket
		DatagramSocket socket = new DatagramSocket(8080);
		
		//2.建个包
		String msg = "你好啊,服务器!";
		InetAddress localhost = InetAddress.getByName("localhost"); 
		int port = 9090;
		
		//参数( 数据,数据的长度,要发送给谁,端口号)
		DatagramPacket packet = new 		           DatagramPacket(msg.getBytes(),msg.getBytes().length,localhost,port);
		
		//3.发送包
		socket.send(packet);
		
		//4.关闭流
		socket.close();
	}
}

接收端

package lesson1.com.p5;

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

public class UdpServerDemo01 {
	public static void main(String[] args) throws Exception {
		//开放端口
		DatagramSocket socket = new DatagramSocket(9090);
		
		//接收数据包
		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();
		
	}
}

循环发送

发送方:

package lesson1.com.p6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class UdpSenderDemo01 {
	public static void main(String[] args) throws Exception {
		
		DatagramSocket socket = new DatagramSocket(8888);
		
		//准备数据,控制台读取System.in
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		
		while(true) {
			String data = reader.readLine();
			byte[] datas = data.getBytes();
			DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
			
			socket.send(packet);	
			if(data.equals("bye")) {
				break;
			}
		}
		socket.close();
	}
}

接收方

package lesson1.com.p6;

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

public class UdpReceiverDemo01 {
	public static void main(String[] args) throws Exception {
		DatagramSocket socket = new DatagramSocket(6666);
		
		while(true) {
			
			//准备接收包裹
			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(receiveData);
			
			if(receiveData.equals("bye")){
				System.out.println("*************");
				break;
			}
		}
		System.out.println("--------------");
		socket.close();
	}
}

在线咨询

两个人都可以是发送方,也都可以是接收方

发送方:

package lesson1.com.p6;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkSend implements Runnable{

	DatagramSocket socket = null;
	BufferedReader reader = null;
	
	private int fromPort;
	private String toIP ;
	private int toPort;
	
	//参数(本机端口号,目的IP,目的IP的端口)
	public TalkSend(int fromPort, String toIP, int toPort) {
		
		this.fromPort = fromPort;
		this.toIP = toIP;
		this.toPort = toPort;
		
		try {
			
			socket = new DatagramSocket(fromPort);
			
			//准备数据,控制台读取System.in
			reader = new BufferedReader(new InputStreamReader(System.in));
		
		} catch (SocketException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	public TalkSend() {
		super();
	}
	
	@Override
	public void run() {
		// TODO 自动生成的方法存根
		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();
	}

}

接收方:

package lesson1.com.p6;

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

public class TalkReceive implements Runnable{
	
	DatagramSocket socket = null;
	private int port;
	private String msgFrom;
	
	//参数(本地接收数据的端口,发送端的名字)
	public TalkReceive(int port,String msgFrom) {
		super();
		this.port = port;
		this.msgFrom = msgFrom;
		try {
			socket = new DatagramSocket(this.port);
		} catch (SocketException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}


	@Override
	public void run() {
		// TODO 自动生成的方法存根
		
		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();
	}
	
}

老师线程:

package lesson1.com.p6;

public class TalkTeacher {
	public static void main(String[] args) {
		//老师向学生的端口8888发送消息
		new Thread(new TalkSend(5555,"localhost",8888)).start();
		//老师的9999端口等待着学生传来的数据
		new Thread(new TalkReceive(9999,"学生")).start();
	}
}


学生线程:

package lesson1.com.p6;

public class TalkStudent {
	public static void main(String[] args) {
		//开启两个线程
		
		//学生向老师的端口9999发送消息
		new Thread(new TalkSend(7777,"localhost",9999)).start();
		//学生的8888端口等待着学生传来的数据
		new Thread(new TalkReceive(8888,"老师")).start();
	}
}

1.8URL

统一资源定位符:定位资源的,定位互联网上的某一个资源

DNS域名解析:将域名解析成一个IP地址

协议://IP.地址:端口/项目名/资源				(可以少,不能多)

通过输入URL来下载资源

package lesson1.com.p7;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UrlDown {
	public static void main(String[] args) throws Exception {
		//1. 下载地址
		URL url = new URL("http://localhost:8080/helleworld");	//""中表示要下载的资源的超链接,即url
		
		//2. 连接到这个资源 HTTP
		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		
		//建立url字节输出流,将url中的资源输出到buffer字节数组中
		InputStream inputStream = urlConnection.getInputStream();
		
		//创建文件流,将读取到的数据读到文件中
		FileOutputStream fos = new FileOutputStream("Laikang.txt");
		byte[] buffer = new byte[1024];
		int len;
		while((len =inputStream.read(buffer))!= -1) {	//从url中读取数据
			fos.write(buffer,0,len);					//将buffer的数据写进文件中
		}
		
		fos.close();
		inputStream.close();
		urlConnection.disconnect();
	}
	
}

1.9总结

1.9.1 IP
  1. 可以使用InetAddress.getByName()来创建一个网络地址,其中的参数可以是

    • 一个32位的点分十进制的ip地址 , 如“127.0.0.1”

    • 或者用localhost表示本机的ip地址,如“ localhost”

    • 可以通 过调用InetAddress.getLocalHost()方法来获取本机的IP地址的网络地址。

    • 也可以用域名来,如"www.baidu.com"

  2. 可以使用InetSocketAddress()来创建一个网络地址,其中有两个参数第一个是IP,第二个是端口

  • 如:
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080);
1.9.3 TCP
  1. 服务器端
  • 可以用ServerSocket来创建服务器的套接字,在使用accept()方法来监听来自客户端的连接,如:
ServerSocket serverSocket = new ServerSocket(9000);	//创建服务器套接字端口
Socket socket = serverSocket.accept();				//创建一个Socket 实例来接收监听到的客户Socket
  1. 客户端
  • 客户端如果要连接到服务器端的话需要知道服务器的地址,因此要先用InetAddress创建一个服务器地址对象,在用Socket连接服务器。如下:
InetAddress serverIP = InetAddress.getByName("127.0.0.1");	//创建服务器的地址对象
socket = new Socket(serverIP,port);	//连接服务器
1.9.4 UDP
  1. UDP虽然是不用连接的,但是依旧要用到Socket,只不过这种Socket是DatagramSocket类型的,因为发送方需要知道接收方的IP地址以及端口,故发送端需创建接收端地址对象,并用DatagramPacket构建好要发送的数据包,使用send()方法发送数据包,而接受端也需要建立

  2. DatagramSocket的Socket来接收发送方的数据,在接收数据之前需要先创建一个DatagramPacket的包对象,用来接收发送方发送来的数据报,接收过程使用的是receiver方法,其是使用阻塞时接收的。

发送方:

		//1.建立一个Socket
		DatagramSocket socket = new DatagramSocket(8080);
		
		//2.建个包
		String msg = "你好啊,服务器!";
		//创建服务器地址对象
		InetAddress localhost = InetAddress.getByName("localhost"); 
		//服务器端口号
		int port = 9090;
		
		//将数据打包,其中参数为:( 数据,数据的长度,目的地址,目的地址的端口号)
		DatagramPacket packet = new 		           DatagramPacket(msg.getBytes(),msg.getBytes().length,localhost,port);
		
		//3.发送包
		socket.send(packet);

接收方:

		//开放端口
		DatagramSocket socket = new DatagramSocket(9090);
		
		//接收数据包
		byte[] buffer = new byte[1024];
		//创建包对象,用于存放接收到的包
		DatagramPacket packet = new DatagramPacket(buffer, 0,buffer.length);
		//将接收到的包存放到packet中
		socket.receive(packet);	//阻塞接受
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值