首页 > 编程语言 >网络编程

网络编程

时间:2022-12-05 21:57:53浏览次数:35  
标签:java socket 编程 网络 import new net public

  • tomcat相关的没操作

IP地址、端口

package com.net.InetAddress_1;
//IP地址    Class InetAddress
//此类表示Internet协议(IP)地址。
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

public class InetAddressDemo01 {
    public static void main(String[] args) {
        try {
            //查询本机地址
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);
            InetAddress inetAddress3 = InetAddress.getByName("localhost");
            System.out.println(inetAddress3);
            InetAddress inetAddress4 = InetAddress.getLocalHost();
            System.out.println(inetAddress4);

            //查询网站ip地址
            InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress2);

            //常用方法
            System.out.println(Arrays.toString(inetAddress2.getAddress()));//[110, -14, 68, 3]
            System.out.println(inetAddress2.getCanonicalHostName());//规范的名字  112.80.248.76
            System.out.println(inetAddress2.getHostAddress());//ip  112.80.248.76
            System.out.println(inetAddress2.getHostName());//域名,或者自己电脑的名字
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }
}
package com.net.InetAddress_1;
//端口Port
//Class InetSocketAddress
//此类实现IP套接字地址(IP地址+端口号)它也可以是一对(主机名+端口号),在这种情况下,将尝试解析主机名。
import java.net.InetAddress;
import java.net.InetSocketAddress;

public class InetSocketAddressDemo02 {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1",4836);
        System.out.println(inetSocketAddress1);

        InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost",4836);
        System.out.println(inetSocketAddress2);

        InetAddress inetAddress = inetSocketAddress1.getAddress();
        System.out.println(inetAddress);
        System.out.println(inetSocketAddress1.getHostName());
        System.out.println(inetSocketAddress1.getPort());
    }
}

TCP

package com.net.tcp_socket_2;
//TCP网络编程 案例一:TCP实现聊天
//客户端
//public class Socket  该类实现客户端套接字(也称为“套接字”)。 套接字是两台机器之间通信的端点。
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TCPClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            socket = new Socket(inetAddress,port);

            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();
                }
            }
        }

    }
}
package com.net.tcp_socket_2;
//TCP网络编程 案例一:TCP实现聊天
//服务端
//public class ServerSocket
//该类实现服务器套接字。服务器套接字等待通过网络进入的请求。它根据该请求执行某些操作,然后可能将结果返回给请求者。
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            serverSocket = new ServerSocket(9999);
            while(true){

                socket = serverSocket.accept();
                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) {
            throw new RuntimeException(e);
        }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();
                }
            }
        }
    }
}
package com.net.tcp_socket_2;
//TCP网络编程 案例二:TCP实现文件上传
//客户端
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TCPClientDemo02 {
    public static void main(String[] args) throws Exception {
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        int port = 9000;
        Socket socket  = new Socket(inetAddress,port);
        OutputStream os = socket.getOutputStream();
        InputStream is = new FileInputStream("C:\\Users\\lcj\\Desktop\\file11\\xueshan.png");
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer))!=-1){
            os.write(buffer,0,len);
        }

        socket.shutdownOutput();

        InputStream socketIS = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        while((len2 = socketIS.read(buffer2)) != -1){
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());

        baos.close();
        socketIS.close();
        is.close();
        os.close();
        socket.close();

    }
}
package com.net.tcp_socket_2;
//TCP网络编程 案例二:TCP实现文件上传
//服务端
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServerDemo02 {
    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(9000);
        Socket socket = serverSocket.accept();
        InputStream is = socket.getInputStream();
        OutputStream os = new FileOutputStream("C:\\Users\\lcj\\Desktop\\file11\\xueshan2.png");

        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer))!=-1) {
            os.write(buffer,0,len);
        }

        OutputStream socketOS = socket.getOutputStream();
        socketOS.write("我已经接收完了,你可以关闭了".getBytes());

        socketOS.close();
        os.close();
        is.close();
        socket.close();
        serverSocket.close();

    }
}

UDP

package com.net.udp_socket_3;
//UDP网络编程 案例一:消息发送
//public class DatagramSocket  此类表示用于发送和接收数据报包的套接字。
//数据报套接字是分组传送服务的发送或接收点。
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Sender01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket();
//        DatagramSocket datagramSocket = new DatagramSocket(8080);//也可成为接收端

        InetAddress inetAddress = InetAddress.getByName("localhost");
        int port = 9090;
        String s = "你好";

        DatagramPacket datagramPacket = new DatagramPacket(
                s.getBytes(),0,s.getBytes().length,inetAddress,port);
        datagramSocket.send(datagramPacket);

        datagramSocket.close();

    }
}
package com.net.udp_socket_3;
//UDP网络编程 案例一:消息发送
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceivingEnd01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket(9090);

        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);

        datagramSocket.receive(datagramPacket);

        System.out.println(
                new String(datagramPacket.getData(),0,datagramPacket.getLength()) );
        System.out.println(datagramPacket.getAddress().getHostAddress());
        System.out.println(datagramPacket.getAddress().getHostName());

        datagramSocket.close();

    }
}
package com.net.udp_socket_3;
//UDP网络编程 案例:聊天实现
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Sender02_01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while(true){
            String line = br.readLine();
            byte[] buffer = line.getBytes();

            DatagramPacket packet = new DatagramPacket(
                    buffer,0, buffer.length, new InetSocketAddress("localhost",6666));

            socket.send(packet);

            if (line.equals("bye")){
                break;
            }
        }

        br.close();
        socket.close();
    }
}
package com.net.udp_socket_3;
//UDP网络编程 案例:聊天实现
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Sender02_02 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        while(true){
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0, buffer.length);

            socket.receive(packet);

            byte[] data = packet.getData();
            String receiveData = new String(data,0,packet.getLength());//要用packet.getLength()  才是准确长度
            System.out.println(receiveData);

            if (receiveData.equals("bye")){
                break;
            }
        }

        socket.close();
    }
}
package com.net.udp_socket_3;
//UDP网络编程 案例:多线程在线咨询聊天
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 Sender03 implements Runnable{
    private DatagramSocket socket = null;
    private String toIP;
    private int toPort;
    private BufferedReader br;
    public Sender03(int fromPort,String toIP,int toPort){
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            this.socket = new DatagramSocket(fromPort);
            br = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void run() {
        while(true){
            try {
                String data = br.readLine();
                byte[] buffer = data.getBytes();
                DatagramPacket packet = new DatagramPacket(
                        buffer,0,buffer.length,new InetSocketAddress(toIP,toPort));

                this.socket.send(packet);

                if (data.equals("bye")){
                    break;
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

//        br.close();//try catch
        socket.close();

    }
}
package com.net.udp_socket_3;
//UDP网络编程 案例:多线程在线咨询聊天
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class ReceivingEnd03 implements Runnable{
    private DatagramSocket socket = null;
    private String msgFrom;

    public ReceivingEnd03(int port,String msgFrom) {
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void run() {

        while(true){

            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0, buffer.length);

            try {
                socket.receive(packet);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            byte[] data = packet.getData();
            String receiveData = new String(data,0,packet.getLength());//要用packet.getLength()  才是准确长度
            System.out.println(msgFrom +":"+receiveData);

            if (receiveData.equals("bye")){
                break;
            }
        }

        socket.close();
    }
}
package com.net.udp_socket_3;
//UDP网络编程 案例:多线程在线咨询聊天
public class Student03 {
    public static void main(String[] args) {
        new Thread(new Sender03(3333,"localhost",7777)).start();
        new Thread(new ReceivingEnd03(9999,"老师")).start();
    }
}
package com.net.udp_socket_3;
//UDP网络编程 案例:多线程在线咨询聊天
public class Teacher03 {
    public static void main(String[] args) {
        new Thread(new Sender03(5555,"localhost",9999)).start();
        new Thread(new ReceivingEnd03(7777,"学生")).start();
    }
}

URL

package com.net.URL_4;
//URL
import java.net.URL;

public class URLDemo01 {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://m701.music.126.net" +
                "/20221204200139/b45943abefb468d13be61b76c8735884" +
                "/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/14096590174/a387/c255/583c" +
                "/256f4b5cb3ca6231095adccdae1d2927.m4a");
        System.out.println(url.getProtocol());
        System.out.println(url.getHost());//获取URL的主机名
        System.out.println(url.getPort());
        System.out.println(url.getPath());
        System.out.println(url.getFile());
        System.out.println(url.getQuery());//获取此URL的查询部分(参数列表)

    }
}
package com.net.URL_4;
//URL下载网络资源  网易云的歌下载
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLDemo02 {
    public static void main(String[] args) throws IOException {
        /*
        URL url = new URL("https://m701.music.126.net/20221204200139/b45943abefb468d13be61b76c8735884/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/14096590174/a387/c255/583c/256f4b5cb3ca6231095adccdae1d2927.m4a");

        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

        InputStream is = httpURLConnection.getInputStream();

        OutputStream os = new FileOutputStream("C:\\Users\\lcj\\Desktop\\file11\\music.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer,0,len);
        }

        os.close();
        is.close();
        httpURLConnection.disconnect();
        */
    }
}

标签:java,socket,编程,网络,import,new,net,public
From: https://www.cnblogs.com/799rijiyuelei/p/16953651.html

相关文章

  • 1500PLC,编程理解
    一,DB块,FB块的高级应用1,同一个FB快可以通过不同的DB快调用,该DB快调用FB快之后,该DB快中的局部变量可以在调用该FB块的FB快内使用,有点拗口:FB400位住线体程序,包含该线体所有......
  • 网络编程基础(1)---OSI七层模型
    网络编程基础(1)心得学习网络编程的核心之一,作为程序员必须要掌握的东西虽在学校学过,同一个东西,初次学习和有经验后的学习感受确实不同需要明白自己在那一层做开发明......
  • day431 spring框架简介 & 2 IOC控制反转 & 3 DI依赖注入、AOP面向切面编程
    SpringSpringframework就是我们平时说的Spring框架,Spring框架是全家桶内其他框架的基础和核心Spring以IoC(控制反转)和AOP(面向切面编程)为内核控制反转IOC(InverseofCon......
  • JavaScript编程语言
    JavaScript编程语言JavaScript(简称“JS”)是一种具有函数优先的轻量级,解释型或即时编译型的编程语言。JavaScript是一种属于网络的高级脚本语言,已经被广泛用于Web应用开......
  • JUC并发编程
    什么是JUCJDK1.5出现的,用来处理线程的工具包进程与线程进程:指在系统中正在运行的一个应用程序;程序一旦运行就是进程;进程一-资源分配的最小单位。线程:系统分配处理器时......
  • 【网络覆盖优化】基于matlab的网络覆盖遗传优化问题仿真
    建立如下的目标函数:  表示的是每一代中被选择在工作状态的节点数目。C'为对应的这些节点的覆盖范围。A为每个节点对应的覆盖范围。基于这个目标函数,我们进行仿真,获......
  • Java 编程基础01
    一、Java开发环境搭建1、开发工具的下载和安装   1)下载方式一:官网下载www.sun.com     www.oracle.com   2)下载方式二:通过搜索下载www.baidu.c......
  • [C++11与并发编程]7、本地变量线程安全
    本地变量线程安全layout:posttitle:本地变量线程安全categories:cpp_concurrencydescription:C++并发编程简介keywords:c++,并发编程,本地变量线程安全​本地变量......
  • [C++11与并发编程]5、使用条件变量和互斥锁实现信号量
    使用条件变量和互斥锁实现信号量layout:posttitle:使用条件变量和互斥锁实现信号量categories:cpp_concurrencydescription:C++并发编程简介keywords:c++,并发编......
  • 什么是网络钓鱼攻击以及它如何影响我的网站?
    如今,网络安全是一个备受关注的话题,“网络钓鱼”这个词也被广泛使用。即使您对病毒、恶意软件或如何在线保护自己一无所知,您也可能在某个时候遇到过这个术语。大多数人都知......