Java网络编程

本文深入探讨了Java网络编程的核心概念,包括TCP和UDP的区别,Socket编程的基本原理,以及如何在服务端使用线程池处理并发请求。通过具体示例展示了如何获取IP地址,解析HTTP内容,以及实现简单的Socket客户端和服务端交互。

Java网络编程
    1.一台JVM和另外一台JVM通信就要采用网络编程,此时必须知道要通信的JVM的IP地址和端口;
    2.Java的网络编程提供了TCP和UDP两种方式其中TCP基于“三次握手”的方式建立起可靠的网络传输协议,UDP并不一定保证发送出去的数据会被接收到,网络上的聊天工具一般都会采用UDP;TCP更安全,UDP速度快;
    3.基于TCP的网络的编程,主要是基于Socket进行编程,服务端是SocketServer会等待客户端的连接,客户端本身就是一个Socket;

   /**
     *获取IP地址,简单内容示例
     * @throws Exception
     */
    public static void getIp() throws Exception{
        InetAddress local = null;
        InetAddress remote = null;
        local = InetAddress.getLocalHost(); //返回本地主机
        //在给定主机名的情况下确定主机的 IP 地址。
        //主机名可以是机器名(如 "java.sun.com"),也可以是其 IP 地址的文本表示形式。如果提供字面值 IP 地址,则仅检查地址格式的有效性。
        remote = InetAddress.getByName("spark.apache.org");
        System.out.println("Local IP: "+local.getHostAddress()); //返回IP地址字符串(以文本表现形式)
        System.out.println("Spark IP: "+ remote.getHostAddress());//返回IP地址字符串(以文本表现形式)
        URL url = new URL("http://spark.apache.org");
        InputStream inputStream = url.openStream();
        Scanner sc = new Scanner(inputStream);
        sc.useDelimiter("\n"); //设置输入的分隔符
        while (sc.hasNext()){
            System.out.println(sc.next());
        }

    }

   /**
     * 获取内容的长度和类型,简单内容示例
     * @throws Exception
     */
    public static void getType() throws Exception{
        URL url = new URL("http://spark.apache.org");
        URLConnection urlConnection = url.openConnection();
        System.out.println("The length: "+urlConnection.getContentLength());
        System.out.println("The Content Type: "+urlConnection.getContentType());
    }

 


    /**
     * Socket编程,简单内容示例
     * @throws Exception
     */
    public static void socketClient() throws  Exception{
        ServerSocket server = null;
        Socket client = null;
        PrintStream output = null;
        server = new ServerSocket(9999);
        System.out.println("------------It's ready to accept client's request-------------");
        client = server.accept();
        output = new PrintStream(client.getOutputStream());
        output.println("I get it!");
        output.close();
        client.close();
        server.close();
    }

 public static void getMessage() throws Exception{
        Socket client = null;
        client = new Socket("localhost",9999);
        BufferedReader bufferedReader = null;
        bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        System.out.println("The content from server is : "+bufferedReader.readLine());
        bufferedReader.close();
        client.close();


    }


    4.在服务端使用线程池来并发处理多个业务;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值