栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 网络编程TCP Socket,ServerSocket 测试 | UDP,URL的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 网络编程TCP Socket,ServerSocket 测试 | UDP,URL的使用

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录
  • 网络编程
    • TCP
      • 测试:InetAddress
      • 测试 InetSocketAddress
      • 客户端与服务端通信
      • 实现文件传输案例
    • UDP
      • 消息发送与接收案例
      • 循环发送消息案例
      • 线程实现对话案例
    • URL
      • 使用url下载资源


网络编程
  • TCP/IP
  • UDP
TCP
测试:InetAddress
public class TestInetAddress {
    public static void main(String[] args) {
        // 查询本机ip
        try {
            InetAddress inet1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inet1);

            InetAddress inet2 = InetAddress.getByName("localhost");
            System.out.println(inet2);

            InetAddress inet3 = InetAddress.getLocalHost();
            System.out.println(inet3);

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


        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
测试 InetSocketAddress
    }
}
测试 InetSocketAddress
public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress address1 = new InetSocketAddress("localhost", 8080);
        System.out.println(address);
        System.out.println(address1);

        System.out.println(address.getAddress());
        System.out.println(address.getHostName()); // 获得地址
        System.out.println(address.getPort()); // 获得端口号

    }
}
客户端与服务端通信

客户端

public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            // 1.要知道服务端的 ip 和 端口号
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9898;
            // 2.创建一个连接
            socket = new Socket(serverIP, port);

            // 3.发送消息, IO流
            os = socket.getOutputStream();
            os.write("你好,欢迎学习Java!".getBytes());

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}

服务端


public class TcpServerDemo01 {
    private static InputStream is = null;
    private static ByteArrayOutputStream baos = null;

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket accept = null;
        try {
            // 1.我得有一个地址
            serverSocket = new ServerSocket(9898);
            while (true) {
                // 2.等待客户端来 连接
                accept = serverSocket.accept();

                // 3.获取消息
                is = accept.getInputStream();
                // 管道流
                baos = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len = is.read(bytes)) != -1 ) {
                    baos.write(bytes, 0, len);
                }
                System.out.println(baos.toString());
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (accept != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}
实现文件传输案例

客户端

public class TcpClientDemo02 {
    public static void main(String[] args) throws IOException {
        // 1.创建客户端,需要地址
        Socket socket = new Socket("127.0.0.1", 7788);
        // 2.创建一个输出流
        OutputStream os = socket.getOutputStream();

        // 3.读取要传输的文件
        FileInputStream fis = new FileInputStream(new File("C:\Users\28416\Pictures\Camera Roll\wolp1.jpg"));
        // 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[] bytes = new byte[1024];
        int l;
        while ((l = is.read(bytes)) != -1) {
            baos.write(bytes, 0, l);
        }
        System.out.println(baos.toString());


        // 关闭资源
        baos.close();
        is.close();
        fis.close();
        os.close();
        socket.close();


    }
}

服务端


public class TcpServerDmo02 {
    public static void main(String[] args) throws IOException {
        // 1.创建服务端
        ServerSocket serverSocket = new ServerSocket(7788);

        // 2.监听客户端的连接
        Socket accept = serverSocket.accept(); // 阻塞式监听,会一直等待客户端连接
        // 3.获取输入流(接受文件)
        InputStream is = accept.getInputStream();

        // 4.文件输出
        FileOutputStream fos = new FileOutputStream("D:\y1\wolp2.jpg");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }


        // 通知客户端,接收完毕
        OutputStream os = accept.getOutputStream();
        os.write("sercer---> 接收完毕!".getBytes());


        // 5.关闭资源
        os.close();
        fos.close();
        accept.close();
        serverSocket.close();


    }
}
UDP
  • UDP不需要连接服务器
消息发送与接收案例

发送端

// 发送端
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        // 1.创建一个Socket
        DatagramSocket socket = new DatagramSocket();

        // 2.建个包
        String msg="发送端--->你好接收端";
        int port = 7878;
        InetAddress localhost = InetAddress.getByName("localhost");

        DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.getBytes().length, localhost, port);

        // 3。发送包
        socket.send(packet);

        // 4.关闭资源
        socket.close();
    }
}

接收端

// 接收端
public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        // 1.开放端口
        DatagramSocket socket = new DatagramSocket(7878);

        // 2.接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(packet); // 阻塞接收

        System.out.println(packet.getAddress());
        System.out.println(new String(packet.getData(),0, packet.getLength()));

        // 关闭资源
        socket.close();
    }
}
循环发送消息案例

发送端

public class UdpClientDemo02 {
    public static void main(String[] args) throws Exception {
        // 1.创建一个Socket
        DatagramSocket socket = new DatagramSocket(9999);

        // 2.准备数据:获取控制台输入的消息
        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",8888));

            // 3。发送包
            socket.send(packet);

            // 4.停止发送
            if (data.equals("bye")) {
                break;
            }
        }

        // 4.关闭资源
        socket.close();
    }
}

接收端

public class UdpServerDemo02 {
    public static void main(String[] args) throws Exception {
        // 1.开放端口
        DatagramSocket socket = new DatagramSocket(8888);

        // 循环接收消息
        while (true) {
            // 2.接收数据包
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
            socket.receive(packet); // 阻塞接收
            String receviceData = new String(packet.getData(), 0, packet.getLength());
            System.out.println(receviceData);

            // 停止接收
            if (receviceData.equals("bye")) {
                break;
            }
        }

        // 关闭资源
        socket.close();
    }
}
线程实现对话案例

发送消息

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class UDPThreadClientDemo implements Runnable {

    BufferedReader reader;
    DatagramSocket socket;
    private int toPort;
    private int myPort;
    private String ip;

    public UDPThreadClientDemo(int myPort, int toPort, String ip) {
        this.toPort = toPort;
        this.ip = ip;
        this.myPort=myPort;
        try {
            // 1.创建一个Socket
            socket = new DatagramSocket(myPort);
            // 2.准备数据:获取控制台输入的消息
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }

    }


    @Override
    public void run() {
        // 循环发送消息
        while (true) {

            try {
                String  data = reader.readLine();  // 读取控制台输入的消息
                byte[] datas = data.getBytes();   // 将消息转换为字节类型

                DatagramPacket packet = new DatagramPacket(datas,0,datas.length , InetAddress.getByName(ip), this.toPort);

                // 3。发送包
                socket.send(packet);

                // 4.停止发送
                if (data.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

        // 4.关闭资源
        socket.close();
    }
}

接收消息

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

public class UDPThreadServerDemo implements Runnable{
    DatagramSocket socket = null;
    private String name;
    private int myPort;

    public UDPThreadServerDemo(int myPort, String name) {
        this.name=name;
        this.myPort=myPort;

        try {
            socket = new DatagramSocket(myPort);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        // 循环接收消息
        while (true) {

            try {
                // 2.接收数据包
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
                socket.receive(packet); // 阻塞接收
                String receviceData = new String(packet.getData(), 0, packet.getLength());
                System.out.println(name+":"+receviceData);

                // 停止接收
                if (receviceData.equals("bye")) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        // 关闭资源
        socket.close();
    }
}

学生测试类

public class TestStudent {
    public static void main(String[] args) {


        new Thread(new UDPThreadClientDemo(3333,8888,"localhost")).start();
        new Thread(new UDPThreadServerDemo(7777, "老师")).start();
    }
}

老师测试类

public class TestTeacher {
    public static void main(String[] args) {
        new Thread(new UDPThreadClientDemo(1111,7777,"localhost")).start();
        new Thread(new UDPThreadServerDemo(8888, "学生")).start();
    }
}

运行效果

URL
使用url下载资源
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestUrl {
    public static void main(String[] args) throws Exception {
        // 1。创建一个地址
        URL url = new URL("https://ts1.cn.mm.bing.net/th/id/R-C.73ea611eef66a0b10bc87b00e50ebdf7?rik=ZDrVzvqpBUylbQ&riu=http%3a%2f%2fimg.17sucai.com%2fupload%2f458%2f2016-05-10%2f601115e868d35345bc778851f29d12b1.jpg%3fx-oss-process%3dstyle%2fpri&ehk=2o1GIUhJ0k963jWX6hTbr98MCsmqKhETYIbTYdK7Yac%3d&risl=&pid=ImgRaw&r=0"); // 这里是一张图片
        // 2.连接到这个资源
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream is = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("地球.jpg");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer,0,len);  // 写出这个数据
        }

        // 关闭资源
        fos.close();
        is.close();
        urlConnection.disconnect(); // 断开连接
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1006118.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号