Java实例——网络实例

news/2024/11/24 18:43:53/

1、主机IP地址获取
步骤一:获取主机InetAddress
步骤二:获取主机IP地址

        InetAddress address = null;try {address = InetAddress.getByName("www.baidu.com");}catch (UnknownHostException e) {System.exit(2);}System.out.println("HostName" + "\t\t"+ "IPAddress");System.out.println(address.getHostName() + "\t\t"+ address.getHostAddress());System.exit(0);

输出结果

HostName		IPAddress
www.baidu.com		180.101.50.242

2、查看端口使用情况

   public static void main(String[] args) {Socket Skt;String host = "localhost";if (args.length > 0) {host = args[0];}for (int i = 0; i < 1024; i++) {try {System.out.println("查看 "+ i);Skt = new Socket(host, i);System.out.println("端口 " + i + " 已被使用");}catch (UnknownHostException e) {System.out.println("Exception occured"+ e);break;}catch (IOException e) {}}}

输出结果

……
查看 17
查看 18
查看 19
查看 20
查看 21
端口 21 已被使用
查看 22
查看 23
查看 24
……

3、获取本机ip地址及主机名

    public static void main(String[] args) throws IOException, InterruptedException {InetAddress inetAddress = InetAddress.getByName("www.baidu.com");System.out.println("主机IP地址:"+inetAddress.getHostAddress());System.out.println("主机名称:"+inetAddress.getHostName());}

输出结果

主机IP地址:180.101.50.242
主机名称:www.baidu.com

4、获取文件大小
步骤一:获取URL对象 new URL(“资源路径”);
步骤二:连接URL链接 URLConnection conn = url.openConnection();
步骤三:获取文件大小 conn.getContentLength();

URL url = new URL("资源路径");	//获取URL对象
URLConnection conn = url.openConnection();	//打开URL资源器
int size = conn.getContentLength();	//文件大小

5、多线程Socket

public class dictoryImpl implements Runnable {Socket clientSocket;public dictoryImpl(Socket clientSocket) {this.clientSocket = clientSocket;}public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(1234);System.out.println("listening");while(true){Socket socket = serverSocket.accept();System.out.println("connectionLocalPort:"+socket.getLocalPort());System.out.println("connectionCurrentPort:"+socket.getPort());new Thread(new dictoryImpl(socket)).start();}}@Overridepublic void run() {try {PrintStream printStream = new PrintStream(clientSocket.getOutputStream());for (int i = 0; i < 100; i++) {printStream.println(i + " bottles of beer on the wall.");}printStream.close();clientSocket.close();} catch (IOException e) {throw new RuntimeException(e);}}
}class client{public static void main(String[] args) throws IOException {Socket socket = new Socket("localhost",1234);socket.close();}
}

输出结果

listening
connectionLocalPort:1234
connectionCurrentPort:3799

6、查看主机指定文件的最后修改时间

    public static void main(String[] args) throws IOException {URL url = new URL("资源路径");URLConnection uc = url.openConnection();uc.setUseCaches(false);long timestamp = uc.getLastModified();System.out.println("java.bmp 文件最后修改时间 :"+timestamp);}

7、使用Socket连接到指定主机

    public static void main(String[] args) throws IOException {InetAddress inetAddress;Socket socket = new Socket("www.baidu.com",80);inetAddress = socket.getInetAddress();System.out.println("连接到 "+inetAddress);socket.close();}

输出结果

连接到 www.baidu.com/180.101.50.188

8、网页抓取

    public static void main(String[] args) throws IOException {URL url = new URL("https://blog.csdn.net/Zain_horse/article/details/129048338");BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));String line;while ((line = bufferedReader.readLine()) != null){System.out.println(line);}bufferedReader.close();}

输出结果
在这里插入图片描述
9、获取响应头日期

    public static void main(String[] args) throws IOException {URL url = new URL("https://blog.csdn.net/Zain_horse/article/details/129048338");HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();long date = httpURLConnection.getDate();SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");if (date == 0){System.out.println("无法获取Header");}else {System.out.println("Date:"+simpleDateFormat.format(date));}}

输出结果

Date:2023-02-22 22:08:26 下午

10、获取相应头信息

    public static void main(String[] args) throws IOException {URL url = new URL("https://blog.csdn.net/Zain_horse/article/details/129048338");HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();Map<String, List<String>> listMap = httpURLConnection.getHeaderFields();Set<String> keySet = listMap.keySet();for (String key:keySet) {String val = httpURLConnection.getHeaderField(key);System.out.println(key+":"+val);}}

输出结果

Keep-Alive:timeout=20
Transfer-Encoding:chunked
null:HTTP/1.1 200 OK
Strict-Transport-Security:max-age= 31536000
Server:openresty
Connection:keep-alive
Set-Cookie:dc_session_id=10_1677075301490.865484; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=.csdn.net;
Vary:Accept-Encoding
Content-Language:en-US
Date:Wed, 22 Feb 2023 14:15:01 GMT
Content-Type:text/html;charset=utf-8

11、解析URL

    public static void main(String[] args) throws IOException {URL url = new URL("https://blog.csdn.net/Zain_horse/article/details/129048338");System.out.println(url);System.out.println(url.getProtocol()+"://"+url.getHost()+url.getPort()+url.getPath());}

输出结果

https://blog.csdn.net/Zain_horse/article/details/129048338
https://blog.csdn.net-1/Zain_horse/article/details/129048338

12、C/S Socekt之间通信

服务器端建立过程:

  • 服务器建立通信ServerSocket
  • 服务器建立Socket接收客户端连接
  • 建立IO输入流读取客户端发送的数据
  • 建立IO输出流向客户端发送数据消息

ServerSocket 服务器端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;public class Server {public static void main(String[] args) {try {ServerSocket ss = new ServerSocket(8888);System.out.println("启动服务器....");Socket s = ss.accept();System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));//读取客户端发送来的消息String mess = br.readLine();System.out.println("客户端:"+mess);BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));bw.write(mess+"\n");bw.flush();} catch (IOException e) {e.printStackTrace();}}
}

客户端Client建立过程:

  • 创建Socket通信,设置通信服务器的IP和Port
  • 建立IO输出流向服务器发送数据消息
  • 建立IO输入流读取服务器发送来的数据消息
    ClientSoceket 客户端
/*author by w3cschool.cnMain.java*/import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;public class Client {public static void main(String[] args) {try {Socket s = new Socket("127.0.0.1",8888);//构建IOInputStream is = s.getInputStream();OutputStream os = s.getOutputStream();BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));//向服务器端发送一条消息bw.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n");bw.flush();//读取服务器返回的消息BufferedReader br = new BufferedReader(new InputStreamReader(is));String mess = br.readLine();System.out.println("服务器:"+mess);} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}
服务器端结果:
启动服务器....客户端结果:
服务器:测试客户端和服务器通信,服务器接收到消息返回到客户端

http://www.ppmy.cn/news/27287.html

相关文章

黑盒测试用例设计方法之等价类划分法

等价类划分法是一种典型的黑盒测试用例设计方法。采用等价类划分法时&#xff0c;完全不用考虑程序内部结构&#xff0c;设计测试用例的唯一依据是软件需求规格说明书。 等价类 所谓等价类&#xff0c;是输入条件的一个子集合&#xff0c;该输入集合中的数据对于揭示程序中的…

AI 生成二次元女孩,免费云端部署(仅需5分钟)

首先需要google的colab&#xff0c;免费版本GPU有额度&#xff0c;因此生成图片悠着点&#xff08;每天重置&#xff09;。&#xff09;其次&#xff0c;需要魔法&#xff0c;打开github网站&#xff0c;选择一个进入colab,修改代码 !apt-get -y install -qq aria2 !pip instal…

每天一道大厂SQL题【Day12】微众银行真题实战(二)

每天一道大厂SQL题【Day12】微众银行真题实战(二) 大家好&#xff0c;我是Maynor。相信大家和我一样&#xff0c;都有一个大厂梦&#xff0c;作为一名资深大数据选手&#xff0c;深知SQL重要性&#xff0c;接下来我准备用100天时间&#xff0c;基于大数据岗面试中的经典SQL题&…

springboot基础

文章目录[toc]SpringBoot概述spring springmvc springboot的关系Spring Boot简介微服务springboot的优点核心功能SpringBoot搭建使用IDEA快速搭建 Spring Boot项目入门案例研究项目结构pom 文件主程序类&#xff0c;主入口类配置文件、加载顺序开启配置文件注释配置文件和加载顺…

逆向-还原代码之max 再画堆栈图 (Interl 64)

// source code #include <stdio.h> void max(int * a, int * b) { if (*a < *b) *a *b; } int main() { int a 5, b 6; max(&a, &b); printf("a, b max %d\n", a); return 0; } // 再画堆栈图 下周一&#xff08;2.27…

双指针 (C/C++)

1. 双指针 双指针算法的核心思想&#xff1a;将暴力解法的时间复杂度&#xff0c;通常是O(N*N)&#xff0c;通过某种特殊的性质优化到O(N)。 做题思路&#xff1a;先想想暴力解法的思路&#xff0c;然后分析这道题的特殊性质&#xff0c;一般是单调性。然后得出双指针算法的思路…

机器学习聚类分析建模方法大全

最近很多私信都在问机器学习的问题&#xff0c;感觉很多都是刚入门的新手&#xff0c;有些概念和问题也相对比较基础&#xff0c;空余时间里我在不断整理一些常用的基础算法模型&#xff0c;写成文章后面有需要的话可以直接阅读即可&#xff0c;有些问题可能直接就迎刃而解了吧…

国内知名插画培训机构有哪些,学习插画怎么选培训班

国内知名插画培训机构有哪些&#xff1f;给大家梳理了国内5家专业的插画师培训班&#xff0c;最新无大插画班排行榜&#xff0c;各有优势和特色&#xff01; 一&#xff1a;国内知名插画培训机构排名 1、轻微课&#xff08;五颗星&#xff09; 主打课程有日系插画、游戏原画…