J2EE练习_chapter14网络编程

简介: J2EE练习_chapter14网络编程

题目01

InetAdressTest

package com.jerry.java;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
 * @author jerry_jy
 * @create 2022-10-12 19:38
 */
public class InetAdressTest {
    public static void main(String[] args) throws UnknownHostException {
        InetAddress address = InetAddress.getByName("www.baidu.com");
        System.out.println(address);//www.baidu.com/36.152.44.96
        System.out.println(address.getHostName());//www.baidu.com
        System.out.println(address.getHostAddress());//36.152.44.96
        System.out.println(InetAddress.getLocalHost());//DESKTOP-PP0IDCV/192.168.56.1
        System.out.println(InetAddress.getByName("192.168.56.1"));///192.168.56.1
    }
}

题目02

/*
实现TCP的网络编程
例子1:客户端发送信息给服务端,服务端将数据显示在控制台上
 */

package com.jerry.java;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @author jerry_jy
 * @create 2022-10-12 20:08
 */
public class TCPTest1 {
    //客户端
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("192.168.56.1");
            socket = new Socket(inet, 8899);
            //2.获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3.写出数据的操作
            os.write("你好,我是客户端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //服务端
    @Test
    public void server() {
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号
            ss = new ServerSocket(8899);
            //2.调用accept()表示接收来自于客户端的socket
            socket = ss.accept();//该方法是一个阻塞式方法。如果没有客户端连接,将一直等待
            System.out.println("一个客户端连接成功!");
            //3.获取输入流
            is = socket.getInputStream();
            //不建议这样写,可能会有乱码
//        byte[] buffer = new byte[1024];
//        int len;
//        while((len = is.read(buffer)) != -1){
//            String str = new String(buffer,0,len);
//            System.out.print(str);
//        }
            //4.读取输入流中的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            System.out.println(baos.toString());
            System.out.println("收到了来自:" + socket.getInetAddress().getHostAddress() + "的数据");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ss != null) {
                    ss.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

题目03

/*
 * 实现TCP的网络编程
 * 例题2:客户端发送文件给服务端,服务端将文件保存在本地。
 * 这里涉及到的异常,应该使用try-catch-finally处理
 */

package com.jerry.java;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @author jerry_jy
 * @create 2022-10-13 11:05
 */
public class TCPTest2 {
    @Test
    public void client() throws IOException {
        //1.创建Socket对象,指明服务器端的ip和端口号
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
        //2.获取一个输出流,用于输出数据
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream("java.jpg");
        //3.写出数据的操作
        byte[] buffer = new byte[1024];
        int len;
        while ((len=fis.read(buffer))!=-1){
            os.write(buffer, 0, len);
        }
        //4.资源的关闭
        os.close();
        fis.close();
        socket.close();
    }
    /*
    这里涉及到的异常,应该使用try-catch-finally处理
     */
    @Test
    public void server() throws IOException {
        //1.创建服务器端的ServerSocket,指明自己的端口号
        ServerSocket ss = new ServerSocket(9999);
        //2.调用accept()表示接收来自于客户端的socket
        Socket socket = ss.accept();
        //3.获取输入流
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("java_1.jpg");
        //4.读取输入流中的数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer, 0, len);
        }
        //5.关闭资源
        fos.close();
        is.close();
        socket.close();
        ss.close();
    }
}

题目04

/*
 * 实现TCP的网络编程
 * 例题3:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。
 * 并关闭相应的连接。
 * 这里涉及到的异常,应该使用try-catch-finally处理
 */

package com.jerry.java;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @author jerry_jy
 * @create 2022-10-13 11:24
 */
public class TCPTest3 {
    @Test
    public void client() throws IOException {
        //1.创建Socket对象,指明服务器端的ip和端口号
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        //2.获取一个输出流,用于输出数据
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream("java.jpg");
        //3.写出数据的操作
        byte[] buffer = new byte[1024];
        int len;
        while ((len=fis.read(buffer))!=-1){
            os.write(buffer, 0, len);
        }
        //4.关闭数据的输出
        socket.shutdownOutput();
        //5.接收来自于服务器端的数据,并显示到控制台上
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff= new byte[1024];
        int len1;
        while ((len1=is.read(buff))!=-1){
            baos.write(buff, 0, len1);
        }
        System.out.println(baos.toString());
        //6.关闭资源
        baos.close();
        is.close();
        fis.close();
        os.close();
        socket.close();
    }
    /*
    这里涉及到的异常,应该使用try-catch-finally处理
     */
    @Test
    public void server() throws IOException {
        //1.创建服务器端的ServerSocket,指明自己的端口号
        ServerSocket ss = new ServerSocket(8888);
        //2.调用accept()表示接收来自于客户端的socket
        Socket socket = ss.accept();
        //3.获取输入流
        InputStream is = socket.getInputStream();//用来接收该客户端发送给服务器的数据
        FileOutputStream fos = new FileOutputStream("java_2.jpg");
        //4.读取输入流中的数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer, 0, len);
        }
        System.out.println("图片传输完成");
        //6.服务器端给予客户端反馈
        OutputStream os = socket.getOutputStream();//获取输出流,用来发送数据给该客户端
        os.write("照片我已收到".getBytes());
        //5.关闭资源
        os.close();
        fos.close();
        is.close();
        socket.close();
        ss.close();
    }
}

题目05

客户端发送数据,服务器端响应

package com.jerry.java;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @author jerry_jy
 * @create 2022-10-13 15:43
 */
public class TCPTest4 {
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        Socket socket = ss.accept();
        System.out.println("一个客户端连接成功");
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        //接受客户端发来的数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            System.out.println(new String(buffer, 0, len));
        }
        //服务器端发数据给客户端
        os.write("欢迎登陆!".getBytes());
        os.flush();
        socket.close();
        ss.close();
    }
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        //客户端发数据
        os.write("客户端发送数据".getBytes());
        os.flush();
        socket.shutdownOutput();
        //客户端接受服务器端发来的数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            System.out.println(new String(buffer, 0, len));
        }
        socket.close();
    }
}

题目06

UDP通信

package com.jerry.java;
import org.junit.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
/**
 * @author jerry_jy
 * @create 2022-10-13 16:44
 */
public class UDPTest {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String str = "我是UDP";
        byte[] data = str.getBytes(StandardCharsets.UTF_8);
        InetAddress localHost = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, localHost, 8888);
        socket.send(packet);
        socket.close();
    }
    //接收端
    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(8888);
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        socket.close();
    }
}

题目07

URL测试

package com.jerry.java;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * @author jerry_jy
 * @create 2022-10-13 16:56
 */
public class URLTest {
    //C:\Users\15718\Desktop
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
//            public String getProtocol(  )     获取该URL的协议名
            System.out.println(url.getProtocol());//http
//            public String getHost(  )           获取该URL的主机名
            System.out.println(url.getHost());//localhost
//            public String getPort(  )            获取该URL的端口号
            System.out.println(url.getPort());//8080
//            public String getPath(  )           获取该URL的文件路径
            System.out.println(url.getPath());///examples/beauty.jpg
//            public String getFile(  )             获取该URL的文件名
            System.out.println(url.getFile());///examples/beauty.jpg?username=Tom
//            public String getQuery(   )        获取该URL的查询名
            System.out.println(url.getQuery());//username=Tom
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

题目08

URL编程

package com.jerry.java;
import javax.net.ssl.HttpsURLConnection;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
 * @author jerry_jy
 * @create 2022-10-13 17:01
 */
public class URLTest1 {
    public static void main(String[] args) {
        URL url = null;
        InputStream is =null;
        FileOutputStream fos =null;
        HttpsURLConnection urlConnection =null;
        try {
            url = new URL("http://localhost:8080/examples/beauty.jpg");
             urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.connect();
             is = urlConnection.getInputStream();
             fos = new FileOutputStream("day10\\beauty3.jpg");
            byte[] buffer = new byte[1024];
            int len;
            while ((len=is.read(buffer))!=-1){
                fos.write(buffer, 0, len);
            }
            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos!=null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (urlConnection!=null){
                urlConnection.disconnect();
            }
        }
    }
}

题目09

/*
1.服务端读取图片并发送给客户端,客户端保存图片到本地
 */

package com.jerry.exer;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @author jerry_jy
 * @create 2022-10-13 15:53
 */
public class Exer1 {
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        Socket socket = ss.accept();
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        FileInputStream fis = new FileInputStream("java.jpg");
        byte[] buffer = new byte[1024];
        int len=0;
        //传输图片
        while ((fis.read(buffer))!=-1){
            os.write(buffer, 0, len);
        }
//        os.write("服务器说发送图片完成".getBytes());
        //4.关闭数据的输出
        socket.shutdownOutput();
        //接受数据
        byte[] buffer1 = new byte[1024];
        int len1;
        while ((len1=is.read(buffer1))!=-1){
            System.out.println(new String(buffer1, 0, len1));
        }
        //5.接收来自于服务器端的数据,并显示到控制台上
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        byte[] buff= new byte[1024];
//        int len1;
//        while ((len1=is.read(buff))!=-1){
//            baos.write(buff, 0, len1);
//        }
//        System.out.println(baos.toString());
//        baos.close();
        os.flush();
        os.close();
        fis.close();
        ss.close();
        socket.close();
    }
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("java_client.jpg");
        byte[] buffer = new byte[1024];
        int len;
        //接受图片
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer, 0, len);
        }
//        socket.shutdownOutput();//关闭数据输出,再传别的
//        os.write("客户端说收到了图片".getBytes());
        System.out.println("图片传输完成");
        os.write("发送图片完成".getBytes());//这句话是写给服务器的
        os.flush();
        //客户端接受服务器端发来的数据
//        byte[] buffer1 = new byte[1024];
//        int len1;
//        while ((len1=is.read(buffer1))!=-1){
//            System.out.println(new String(buffer1, 0, len1));
//        }
        socket.close();
    }
}

题目10

/*
客户端给服务端发送文本,服务端会将文本转成大写在返回给客户端
 */

package com.jerry.exer;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Locale;
/**
 * @author jerry_jy
 * @create 2022-10-13 16:27
 */
public class Exer2 {
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        String str ="";
        while ((len=is.read(buffer))!=-1){
             str = new String(buffer, 0, len);
        }
        //服务器端发数据给客户端
        os.write(str.toUpperCase(Locale.ROOT).getBytes());
        os.flush();
        socket.close();
        ss.close();
    }
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        os.write("abcdefghj".getBytes());
        os.flush();
        socket.shutdownOutput();
        //客户端接受服务器端发来的数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            System.out.println(new String(buffer, 0, len));
        }
        socket.close();
    }
}

题目11

用JAVA SOCKET编程,读服务器几个字符,再写入本地显示

package com.jerry.exer1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
    private ServerSocket ss;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    public Server() {
        try {
            ss = new ServerSocket(10000);
            while (true) {
                socket = ss.accept();
                String RemoteIP = socket.getInetAddress().getHostAddress();
                String RemotePort = ":" + socket.getLocalPort();
                System.out.println("A client come in!IP:" + RemoteIP + RemotePort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = in.readLine();
                System.out.println("Client send is :" + line);
                out = new PrintWriter(socket.getOutputStream(), true);
                out.println("Your Message Received!");
                out.close();
                in.close();
                socket.close();
            }
        } catch (IOException e) {
            out.println("wrong");
        }
    }
    public static void main(String[] args) {
        new Server();
    }
}

package com.jerry.exer1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
    Socket socket;
    BufferedReader in;
    PrintWriter out;
    public Client() {
        try {
            System.out.println("Try to Connect to 127.0.0.1:10000");
            socket = new Socket("127.0.0.1", 10000);
            System.out.println("The Server Connected!");
            System.out.println("Please enter some Character:");
            BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println(line.readLine());
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(in.readLine());
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            out.println("Wrong");
        }
    }
    public static void main(String[] args) {
        new Client();
    }
}

题目12

/*
编写一个服务器和一个客户端
1)服务器可以读取本地文件内容并能将内容发给请求的客户端
2)再编写一个可以发请求到服务器,并能从服务器段获取文件内容的客户端
 */

package com.jerry.exer1;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @author jerry_jy
 * @create 2022-10-13 17:15
 */
public class Exer1 {
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        Socket socket = ss.accept();
        FileInputStream fis = new FileInputStream("java.jpg");
        OutputStream os = socket.getOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((fis.read(buffer))!=-1){
            os.write(buffer, 0, len);
        }
        System.out.println("图片传输完成");
        os.write("照片我已收到".getBytes());
        os.flush();
        os.close();
        fis.close();
        socket.close();
        ss.close();
    }
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("java_3.jpg");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer, 0, len);
        }
        socket.shutdownOutput();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len1;
        while ((len1=is.read(buff))!=-1){
            baos.write(buff, 0, len1);
        }
        System.out.println(baos.toString());
        baos.close();
        fos.close();
        is.close();
        socket.close();
    }
}

题目13

/*网络编程
1)  用网络编程编写一个服务端
2)  编写一个客户端,客户端向服务端发送一条信息
3)  服务端在这条信息前面加上“服务端:”后再返给客户端输出。
 */

package com.jerry.exer1;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @author jerry_jy
 * @create 2022-10-13 17:44
 */
public class Exer2 {
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        String str = "";
        while ((len=is.read(buffer))!=-1){
            str = new String(buffer,0,len);
        }
        os.write(("服务端:"+str).getBytes());
        os.flush();
        socket.close();
        ss.close();
    }
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        os.write("客户端向服务端发送一条信息".getBytes());
        os.flush();
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            System.out.println(new String(buffer, 0, len));
        }
        socket.close();
    }
}

题目14

/*
网络聊天功能(50分)
1)  用网络编程编写一个服务端(5分)
2)  用网络编写一个客户端(5分)
3)  客户端输入 client,服务端响应 I'SERVER!(40分)
 */

package com.jerry.exer1;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @author jerry_jy
 * @create 2022-10-13 17:57
 */
public class Exer3 {
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        Socket socket = ss.accept();
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        //接受客户端发来的数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            System.out.println(new String(buffer, 0, len));
        }
        os.write("I'SERVER!".getBytes());
        os.flush();
        socket.close();
        ss.close();
    }
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        os.write("client".getBytes());
        os.flush();
        socket.shutdownOutput();
        //客户端接受服务器端发来的数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            System.out.println(new String(buffer, 0, len));
        }
        socket.close();
    }
}

题目15

/*
利用UDP编写一个程序,通过这个程序将一个字符串传给另外一台电脑中同样的程序
 */

package com.jerry.exer1;
import org.junit.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
/**
 * @author jerry_jy
 * @create 2022-10-13 18:07
 */
public class Exer4 {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String str= "发送字符串";
        byte[] data = str.getBytes(StandardCharsets.UTF_8);
        InetAddress host = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, host,8888);
        socket.send(packet);
        socket.close();
    }
    //接收端
    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(8888);
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        socket.close();
    }
}

题目16

/*
利用UDP编写一个程序,通过这个程序将键盘输入的一句话传给其他多台电脑中同样的程序
 */

package com.jerry.exer1;
import org.junit.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.Buffer;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
/**
 * @author jerry_jy
 * @create 2022-10-13 18:14
 */
public class Exer5 {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String str = "hello ";
        byte[] data = str.getBytes(StandardCharsets.UTF_8);
        InetAddress host = InetAddress.getLocalHost();
        DatagramPacket packet1 = new DatagramPacket(data, data.length, host, 8888);
        DatagramPacket packet2 = new DatagramPacket(data, data.length, host, 8889);
        socket.send(packet1);
        socket.send(packet2);
        socket.close();
    }
    //接收端
    @Test
    public void receiver1() throws IOException {
            receive(8888);
    }
    //接收端
    @Test
    public void receiver2() throws IOException {
            receive(8889);
    }
    public static void receive(int port) throws IOException{
        DatagramSocket socket = new DatagramSocket(port);
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        socket.close();
    }
}

题目17

/*
利用UDP和TCP实现
a)  服务器利用UDP将自己的IP和端口号发送给客户端
b)  客户端依据服务器段返回的IP和端口号,利用TCP连接到服务器
 */
package com.jerry.exer1;
import org.junit.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
/**
 * @author jerry_jy
 * @create 2022-10-13 18:29
 */
public class Exer6 {
    @Test
    public void server() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        String port = "8888";
        byte[] hostName = hostAddress.getBytes(StandardCharsets.UTF_8);
        byte[] portNum = port.getBytes(StandardCharsets.UTF_8);
        InetAddress localHost = InetAddress.getLocalHost();
        DatagramPacket packet1 = new DatagramPacket(hostName, 0, hostName.length,localHost,8888);
        DatagramPacket packet2 = new DatagramPacket(portNum, 0, portNum.length,localHost,8888);
        socket.send(packet1);
        socket.send(packet2);
        socket.close();
    }
    @Test
    public void client() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        socket.close();
    }
}

END

相关文章
|
开发框架
J2EE练习及面试题_chapter13 IO流_下
J2EE练习及面试题_chapter13 IO流_下
|
开发框架 Java
J2EE练习及面试题_chapter13 IO流_中
J2EE练习及面试题_chapter13 IO流_中
|
开发框架
J2EE练习及面试题_chapter13 IO流_上
J2EE练习及面试题_chapter13 IO流_上
|
开发框架
J2EE练习_chapter16Java8新特性
J2EE练习_chapter16Java8新特性
|
开发框架
J2EE练习_chapter16Java8新特性_练习题
J2EE练习_chapter16Java8新特性_练习题
Java2EE基础练习及面试题_chapter04面向对象(上_03)
Java2EE基础练习及面试题_chapter04面向对象(上_03)
|
存储 Java
Java2EE基础练习及面试题_chapter05面向对象(中_03)
Java2EE基础练习及面试题_chapter05面向对象(中_03)
Java2EE基础练习及面试题_chapter04面向对象(上_01)
Java2EE基础练习及面试题_chapter04面向对象(上_01)