Experiment 7 Java network programming

table of Contents

1. The purpose of the experiment

2. Experimental code

1. Use the URL to read the content of the file in the web server and display it on the console.

2. Use the method of InetAddress class to obtain the IP address of the host of www.baidu.com (or other domain names); obtain the name and IP address of the local machine.

3. Use Socket class and ServerSocket class to write a C/S program to realize C/S communication.

4. Write a program to realize network file transmission.

One word per text


1. The purpose of the experiment

1 . Understand the use of URL classes;

2. Master the use of InetAddress class;

3 . Master the Socket communication method, master the use of Socket class , master the use of ServerSocket class, and master the application of communication using C/S mode.

2. Experimental code

1. Use the URL to read the file content in the web server and display it on the console.

The address of the network server is self-made. If the address can be

https://news.163.com/20/1123/10/FS43N0VS000189FH.html?clickfrom=w_yw

package 作业练习.test7;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Study_1 {
    public static void main(String[] args) throws Exception {
        // 构建一URL对象
        URL baidu = new URL("https://news.163.com/20/1123/10/FS43N0VS000189FH.html?clickfrom=w_yw");
        //由URL对象获取URLConnection对象
        URLConnection uc=baidu.openConnection();
        //由URLConnection获取输入流,并构造BufferedReader对象
        BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String inputLine;
        // 循环读取并打印数据
        while ((inputLine = br.readLine()) != null)
            System.out.println(inputLine);
        // 关闭输入流
        br.close();
    }
}

2. Use the method of InetAddress class to get the IP address of the host of www.baidu.com (or other domain names) ; get the name and IP address of the local machine .

package 作业练习.test7;

import java.io.*;
import java.net.*;
public class Study_2 {
    public static void main(String[] args) {
        String url = "www.baidu.com";      //任意一个网站的域名
        InetAddress ip = null;
        try {
            ip = InetAddress.getByName(url);   //得到对应的IP地址
            InetAddress ipv4 = InetAddress.getLocalHost();
            String nativeip = ipv4.getHostAddress().toString(); // Get local IP Address
            System.out.println("Local IP Address: " + nativeip);
            System.out.println("域名" + url + "对应的IP地址是:" + ip.toString());
        } catch (UnknownHostException e) {
            System.out.println("输入的URL有错!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }}

3. Use Socket class and ServerSocket class to write a C/S program to realize C/S communication.

The client sends a Start command to the server , and the server returns the current time of the server to the client after receiving the string; the client sends an Exit command to the server , and the server returns " Bye " to the client and then exits.

Suggestion: Two students can work in a group, one student simulates the server side and the other simulates the client side .

package 作业练习.test7;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Study_3
{
    public static void main(String args[])
    {
        try
        {
            Socket socket=new Socket("127.0.0.1",9000);//向本机的9000端口发出客户请求
            System.out.println("客户端开启");
            BufferedReader in=new BufferedReader(new InputStreamReader(System.in));//InputStreamReader是字节流通向字符流的桥梁,从底层流读取字节

            //BufferedReader 从字符输入流中读取文本
            PrintWriter os=new PrintWriter(socket.getOutputStream());//getOutputStream()返回此套接字的输出流
            String readline;
            readline=in.readLine();
            while(!readline.equals("bye"))//若读入的字符串为bye,就停止循环
            {
                os.println(readline);//将读入的字符串输出到Server
                os.flush();//刷新输出流,使Server马上收到该字符串
                readline=in.readLine();
            }
            os.close();//关闭Socket输出流
            socket.close();//关闭Socket
        }catch(IOException e){System.out.println("error:"+e);}
    }
}

 

package 作业练习.test7;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Study_3
{
    public static void main(String args[])
    {
        try
        {
            Socket socket=new Socket("127.0.0.1",9000);//向本机的9000端口发出客户请求
            System.out.println("客户端开启");
            BufferedReader in=new BufferedReader(new InputStreamReader(System.in));//InputStreamReader是字节流通向字符流的桥梁,从底层流读取字节

            //BufferedReader 从字符输入流中读取文本
            PrintWriter os=new PrintWriter(socket.getOutputStream());//getOutputStream()返回此套接字的输出流
            String readline;
            readline=in.readLine();
            while(!readline.equals("bye"))//若读入的字符串为bye,就停止循环
            {
                os.println(readline);//将读入的字符串输出到Server
                os.flush();//刷新输出流,使Server马上收到该字符串
                readline=in.readLine();
            }
            os.close();//关闭Socket输出流
            socket.close();//关闭Socket
        }catch(IOException e){System.out.println("error:"+e);}
    }
}

 

4. Write a program to realize network file transmission.

Requirements: To realize the network transmission of picture files, it is necessary to ensure that the client can receive the complete picture files.

package 作业练习.test7;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
//客户端:上传图片
public class CUploadPhotoClient {
    public static void main(String[] args) throws Exception{
        //1.连接诶服务器
        Socket s = new Socket("192.168.190.1",5612);
        System.out.println("已连接到服务器5612端口,准备传送图片...");
        //获取图片字节流
        FileInputStream fis = new FileInputStream("E:\\Intellij IDEL\\project\\src\\作业练习\\test7\\11.png");
        //获取输出流
        OutputStream out = s.getOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        //2.往输出流里面投放数据
        while ((len = fis.read(buf)) != -1)
        {
            out.write(buf,0,len);
        }
        //通知服务端,数据发送完毕
        s.shutdownOutput();
        //3.获取输出流,接受服务器传送过来的消息“上传成功”
        InputStream in = s.getInputStream();
        byte[] bufIn = new byte[1024];
        int num = in.read(bufIn);
        System.out.println(new String(bufIn,0,num));
        //关闭资源
        fis.close();
        out.close();
        in.close();
        s.close();
    }
}

 

package 作业练习.test7;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class CUploadPhotoServer {

    public static void main(String[] args) throws Exception{
        //1.服务器开始监听5612端口
        ServerSocket ss = new ServerSocket(5612);
        System.out.println("服务端已启动,正在监听5612端口...");
        //等待客户端
        Socket s = ss.accept();
        System.out.println("检测到客户端,准备数据接收...");
        //客户端已连接,获取输入流
        InputStream in = s.getInputStream();
        //创建图片字节流
        FileOutputStream fos = new FileOutputStream("server.png");
        byte[] buf = new byte[1024];
        int len = 0;
        //往字节流里写图片数据
        while ((len = in.read(buf)) != -1)
        {
            fos.write(buf,0,len);
        }
        //获取输出流,准备给客户端发送消息
        OutputStream out = s.getOutputStream();
        out.write("上传成功".getBytes());
        //关闭资源
        fos.close();
        in.close();
        out.close();
        s.close();
        ss.close();
    }

}

One word per text

Rather than give yourself a reverie about the future, it is better to add something to your current time!

 

Guess you like

Origin blog.csdn.net/weixin_47723732/article/details/112952584