1、IP
//测试IP public class InetAddressDemo01 { 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.baidu.com"); System.out.println(inetAddress4); System.out.println(inetAddress4.getCanonicalHostName());//规范的名字 System.out.println(inetAddress4.getHostAddress());//ip System.out.println(inetAddress4.getHostName());//域名,或者自己本机名字 } catch (UnknownHostException e) { e.printStackTrace(); } } }
2、端口
端口表示计算机上的一个程序的进程:
-
不同的进程有不同的端口号,用来区分程序
-
端口号0~65535,不能冲突
-
端口分类
-
共有端口 0~1023
-
HTTP:80
-
HTTPS:443
-
FTP:21
-
Telnet:23
-
-
程序注册端口 1024~49151,分配用户或者程序
-
Tomcat:8080
-
Mysql:3306
-
Oracle:1521
-
-
动态、私有:49152~65535
-
netstat -ano //查看所有端口 netstat -ano|findstr "5900" //查看指定端口 tasklist |findstr "15892" //查看指定PID进程
public class InetSocketAddressDemo01 { public static void main(String[] args) { InetSocketAddress socketAddress = new InetSocketAddress("localhost", 8080); System.out.println(socketAddress); System.out.println(socketAddress.getHostName());//hostname System.out.println(socketAddress.getAddress());//ip System.out.println(socketAddress.getPort());//端口 } }
3、TCP
TCP稳定连接,有客户端和服务端。
客户端
-
连接服务端:Socket
-
发送消息:getOutputStream
public class TcpClientDemo01 { public static void main(String[] args) { Socket socket = null; OutputStream os = null; try { //1.知道服务端的端口和地址 InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); int port = 9999; //2.创建一个socket连接 socket = new Socket(inetAddress,port); //3.给服务端传输消息 os = socket.getOutputStream(); os.write("好好学习,天天向上".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
服务端
-
建立服务端的端口:ServerSocket
-
等待客户端的连接:accept()
-
接收客户端的消息:管道流实现ByteArrayOutputStream
public class TcpServerDemo01 { 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) { e.printStackTrace(); }finally { //关闭资源 if(baos!=null){ try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket!=null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
4、文件上传
客户端
public class TcpClientDemo02 { public static void main(String[] args) throws IOException { //1.连接服务端地址 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),8888); //2.向服务端传输文件 OutputStream os = socket.getOutputStream(); //3.读取输入文件 FileInputStream fis = new FileInputStream(new File("ceshi.txt"));//文件需要放在根目录下 //4.写出输入文件 byte[] buffer = new byte[1024]; int len; while ((len=fis.read(buffer))!=-1){ os.write(buffer,0,len); } //通知服务端,我已传输完毕 socket.shutdownOutput(); //确定服务端已接收完毕,断开连接 InputStream is = socket.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer2 = new byte[1024]; int len2; while ((len2= is.read(buffer2))!=-1){ baos.write(buffer2,0,len2); } System.out.println(baos.toString()); //关闭资源 baos.close(); is.close(); fis.close(); os.close(); socket.close(); } }
服务端
public class TcpServerDemo02 { public static void main(String[] args) throws IOException { //1.创建服务端地址 ServerSocket serverSocket = new ServerSocket(8888); //2.等待客户端连接 Socket socket = serverSocket.accept(); //3.接收客户端文件 InputStream is = socket.getInputStream(); //4.文件输出 FileOutputStream fos = new FileOutputStream(new File("receive.txt")); 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(); } }
5、UDP
UDP不稳定连接,没有客户端和服务端。只有发送端和接收端
发送端
//发送端 public class UdpSendDemo01 { public static void main(String[] args) throws Exception { //1.建立一个socket DatagramSocket socket = new DatagramSocket(); //2.建个包 String msg = "你好,接收端"; InetAddress inetAddress = InetAddress.getByName("localhost"); int port = 9090; //发送给谁,数据 DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,inetAddress,port); //3.发送包 socket.send(packet); //关闭资源 socket.close(); } }
接收端
//接收端 public class UdpReceiveDemo01 { public static void main(String[] args) throws Exception { //1.开发端口 DatagramSocket socket = new DatagramSocket(9090); //2.接收数据包 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(); } }
5.1、单方面发送消息
发送端
public class UdpSendDemo01 { public static void main(String[] args) throws Exception { //创建一个socket连接 DatagramSocket socket = new DatagramSocket(9000); //读取输入数据 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); //输入bye,断开连接 if (data.equals("bye")){ break; } } reader.close(); socket.close(); } }
接收端
public class UdpReceiveDemo01 { public static void main(String[] args) throws Exception { //创建一个socket连接 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.trim());//trim()去掉两端多余的空格 //接收到bye,断开连接 if(receiveData.trim().equals("bye")){//没加trim(),接收端无法退出循环,因为字符串后面还有空格 break; } } socket.close(); } }
5.2、互相发送消息(聊天)
利用多线程
-
创建两个类:一个发送端、一个接收端。
-
举例学生和老师:
-
学生即是发送端,也是接收端;老师即是发送端,也是接收端
-
当学生发送消息时,学生是发送端,老师是接收端
-
当老师发送消息时,老师是发送端,学生是接收端
-
发送端
public class TalkSendDemo01 implements Runnable{ //提升作用域 DatagramSocket socket =null; BufferedReader reader = null; private int fromPort;//发送端自己端口 private String toIP;//要发送的地址(接收端) private int toPort;//要发送的端口(接收端) public TalkSendDemo01(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 (Exception e) { e.printStackTrace(); } } @Override public void run() { try { while (true) { //获取输入数据 String data = reader.readLine(); byte[] buffer = data.getBytes(); //打包数据到数据包中,包括接收端的IP和端口 DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress(this.toIP, this.toPort)); //发送数据包 socket.send(packet); //当输入bye,发送包后断开连接 if (data.equals("bye")) { break; } } //关闭资源 reader.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }
接收端
public class TalkReceiveDemo01 implements Runnable { //提升作用域 private int fromPort;//接收端自己端口 private String msg;//发送端的名字 DatagramSocket socket = null; public TalkReceiveDemo01(int fromPort, String msg) { this.fromPort = fromPort; this.msg = msg; try { socket = new DatagramSocket(fromPort); } catch (Exception 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(msg+"端口"+packet.getPort()+":"+receiveData.trim()); //接收到bye后,断开连接 if (receiveData.trim().equals("bye")){//trim(),去掉多余的空格 break;} } catch (Exception e) { e.printStackTrace(); } } //关闭资源 socket.close(); } }
学生
-
发送端口:8888;发送消息时:8888--------->9090
-
接收端口:6666;接收消息时:6666<---------9999
public class TalkStudent { public static void main(String[] args) { //开启两个线程 //当学生发消息时,8888是学生发送端端口,9090是老师接收端端口 new Thread(new TalkSendDemo01(8888,"localhost",9090)).start(); //当学生收到消息时,6666是学生接收端端口 new Thread(new TalkReceiveDemo01(6666,"老师")).start(); } }
老师
-
发送端口:9999;发送消息时:9999--------->6666
-
接收端口:9090;接收消息时:9090<---------8888
public class TalkTeacher { public static void main(String[] args) { //开启两个线程 //当老师发消息时,9999是老师发送端端口,6666是学生接收端端口 new Thread(new TalkSendDemo01(9999,"localhost",6666)).start(); //当老师收到消息时,9090是老师接收端端口 new Thread(new TalkReceiveDemo01(9090,"学生")).start(); } }
6、URL
统一资源定位符:定位互联网上的某一个资源
协议://ip:端口/项目名/资源
public class UrlDemo01 { public static void main(String[] args) throws MalformedURLException { URL url = new URL("http://192.168.1.1:8080/helloworld/index.jsp?username=xuexi&password=123456"); System.out.println(url.getProtocol());//协议 http System.out.println(url.getHost());//主机IP 192.168.1.1 System.out.println(url.getPort());//端口 8080 System.out.println(url.getPath());//文件 /helloworld/index.jsp System.out.println(url.getFile());//全路径 /helloworld/index.jsp?username=xuexi&password=123456 System.out.println(url.getQuery());//参数 username=xuexi&password=123456 } }
实际从网站上下载资源
public class UrlDownDemo01 { public static void main(String[] args) throws Exception { //1.下载地址 URL url = new URL("https://m701.music.126.net/20220410171543/193310eea75ac4d87dd310bc75a69a11/jdyyaac/0658/0108/0209/12abcbb53f6be0d4c17f5c04b6df7a0b.m4a"); //2.连接到这个资源 HTTP HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream is = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream("f.m4a"); byte[] buffer = new byte[1024]; int len; while ((len=is.read(buffer))!=-1){ fos.write(buffer,0,len);//写出这个数据 } //关闭资源 fos.close(); is.close(); urlConnection.disconnect();//断开连接 } }