【0基础学java】教学日志:javaSE-- 网络编程

本章概述:本章主要讲了网络的基本概念,网络分层,数据的封装与拆分网络爬虫原理和比较重要的TCP编程和UDP编程

目录

本章概述:

一、InetAddressDemo

二、Server

1、Server

2、Server2

3、LoginServer

4、LoginServer2

5、LoginThread

6、PicServer

7、UDPServer

三、Client

1、Client

2、Client2

3、LoginClient

4、PicClient

5、UDPClient

5、User


本章概述:

一、InetAddressDemo

package com.tensent.class4;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/27 - 04 - 27 - 8:56
 * @Description: com.tensent.class4
 * @version: 1.0
 */
public class InetAddressDemo {

    public static void main(String[] args) throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println(inetAddress);

        InetAddress address = InetAddress.getByName("www.baidu.com");
        System.out.println(address);
        System.out.println(address.getHostName());
        System.out.println(address.getHostAddress());

    }
}

二、Server

1、Server

package com.tensent.class4.server;

import sun.plugin2.message.transport.SerializingTransport;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/27 - 04 - 27 - 9:19
 * @Description: com.tensent.class4.server
 * @version: 1.0
 *
 * 服务器程序
 */
public class Server {

    public static void main(String[] args) throws IOException {
        //创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(10086);
        System.out.println("**********************服务器已开启... ...**********************");
        //开启一个监听
        Socket server = serverSocket.accept();
        //从socket对象中获取输入流
        InputStream inputStream = server.getInputStream();
        //使用DataInputStream包装流
        DataInputStream dataInputStream = new DataInputStream(inputStream);
        //读取从客户端发送过来的数据
        String s = dataInputStream.readUTF();
        System.out.println("客户端说:" + s);
        //关闭资源
        dataInputStream.close();
        inputStream.close();
        server.close();
        serverSocket.close();
    }
}

2、Server2

package com.tensent.class4.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/27 - 04 - 27 - 9:34
 * @Description: com.tensent.class4.server
 * @version: 1.0
 */
public class Server2 {

    public static void main(String[] args) throws IOException {
        //创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(10000);
        System.out.println("**********************服务器已开启... ...**********************");
        //开启监听
        Socket server = serverSocket.accept();
        /**************************接收从客户端发送的消息*******************************/
        InputStream inputStream = server.getInputStream();
        byte[] buffer = new byte[1024];
        int length = inputStream.read(buffer);
        System.out.println("客户端说:" +new String(buffer,0,length));

        /**************************服务器向客户端响应一条消息*******************************/
        OutputStream outputStream = server.getOutputStream();
        //向客户端传输数据
        outputStream.write("我已收到你的消息,我是服务器!".getBytes());

        //关闭资源
         outputStream.close();
         inputStream.close();
         server.close();
         serverSocket.close();
    }
}

3、LoginServer

package com.tensent.class6.server;

import com.tensent.class6.client.User;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 10:36
 * @Description: com.tensent.class6.server
 * @version: 1.0
 */
public class LoginServer {

    public static void main(String[] args) throws Exception {
//        ServerSocket serverSocket = new ServerSocket(10008);
//        System.out.println("****************服务器启动... ...****************");
//        Socket server = serverSocket.accept();
//        InputStream inputStream = server.getInputStream();
//        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
//        User user = (User)objectInputStream.readObject();
//        //验证用户是否合法
//        String str = "";
//        if("jason".equals(user.getUsername()) && "123456".equals(user.getPassword())){
//            str = "登录成功!";
//        }else{
//            str = "登录失败!";
//        }
//        server.shutdownInput();
//
//        OutputStream outputStream = server.getOutputStream();
//        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
//        dataOutputStream.writeUTF(str);
//
//        //关闭资源
//        dataOutputStream.close();
//        outputStream.close();
//        objectInputStream.close();
//        server.close();
//        serverSocket.close();

        /**************************服务器循环监听客户端的请求****************************/
            ServerSocket serverSocket = new ServerSocket(10008);
            System.out.println("****************服务器启动... ...****************");
        while(true){
            Socket server = serverSocket.accept();
            InputStream inputStream = server.getInputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            User user = (User)objectInputStream.readObject();
            //验证用户是否合法
            String str = "";
            if("jason".equals(user.getUsername()) && "123456".equals(user.getPassword())){
                str = "登录成功!";
                System.out.println("欢迎----【" + user.getUsername() + "】----登录系统!");
            }else{
                str = "登录失败!";
            }
            server.shutdownInput();

            OutputStream outputStream = server.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(str);

            //关闭资源
            dataOutputStream.close();
            outputStream.close();
            objectInputStream.close();
            server.close();
        }
//        serverSocket.close();
    }
}

4、LoginServer2

package com.tensent.class6.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 11:05
 * @Description: com.tensent.class6.server
 * @version: 1.0
 */
public class LoginServer2 {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(10008);
        System.out.println("****************服务器启动... ...****************");

        while(true){
            Socket server = serverSocket.accept();
            LoginThread loginThread = new LoginThread(server);
            new Thread(loginThread).start();
        }
    }
}

5、LoginThread

package com.tensent.class6.server;

import com.tensent.class6.client.User;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 10:51
 * @Description: com.tensent.class6.server
 * @version: 1.0
 */
public class LoginThread implements Runnable{

    private Socket socket;

    public LoginThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        ObjectInputStream objectInputStream = null;
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            inputStream = socket.getInputStream();
             objectInputStream = new ObjectInputStream(inputStream);
            User user = (User)objectInputStream.readObject();
            //验证用户是否合法
            String str = "";
            if("jason".equals(user.getUsername()) && "123456".equals(user.getPassword())){
                str = "登录成功!";
                System.out.println("欢迎----【" + user.getUsername() + "】----登录系统!");
            }else{
                str = "登录失败!";
            }
            socket.shutdownInput();

            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(str);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭资源
                dataOutputStream.close();
                outputStream.close();
                objectInputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

6、PicServer

package com.tensent.class6.server;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 10:18
 * @Description: com.tensent.class6.server
 * @version: 1.0
 */
public class PicServer {

    public static void main(String[] args) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("23_jordan.jpg");
        //创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(10086);
        System.out.println("********************服务器已开启... ...*******************");
        //开启监听
        Socket server = serverSocket.accept();
        //从socket中获取输入流
        InputStream inputStream = server.getInputStream();
        //读取客户端发送的文件数据,同时写入到服务端
        byte[] buffer = new byte[1024];
        int length = 0;
        while((length = inputStream.read(buffer))!=-1){
            fileOutputStream.write(buffer,0,length);
        }
        server.shutdownInput();

        //服务器给客户端响应一条信息
        OutputStream outputStream = server.getOutputStream();
        outputStream.write("上传成功!".getBytes());
        server.shutdownOutput();

        //关闭资源
        outputStream.close();
        inputStream.close();
        fileOutputStream.close();
        server.close();
        serverSocket.close();

    }
}

7、UDPServer

package com.tensent.class6.server;

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

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 11:15
 * @Description: com.tensent.class6.server
 * @version: 1.0
 */
public class UDPServer {

    public static void main(String[] args) throws Exception {
        //创建DatagramSocket对象
        DatagramSocket datagramSocket = new DatagramSocket(10086);
        //接收消息
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer,buffer.length);
        datagramSocket.receive(datagramPacket);
        System.out.println("UDPClient说:" + new String(datagramPacket.getData(),0,datagramPacket.getLength()));
        //关闭资源
        datagramSocket.close();
    }
}

三、Client

1、Client

package com.tensent.class4.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/27 - 04 - 27 - 9:19
 * @Description: com.tensent.class4.client
 * @version: 1.0
 *
 * 模拟客户端向服务器发送一条消息
 *
 * 客户端程序
 */
public class Client {

    public static void main(String[] args) throws IOException {
        //创建Socket套接字对象
        Socket client = new Socket("localhost",10086);
        //从socket中获取输出流
        OutputStream outputStream = client.getOutputStream();
        //使用DataOutputStream包装流
        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
        //发送一条信息给服务器
        dataOutputStream.writeUTF("你好,服务器,我是客户端!");
        //关闭资源
        dataOutputStream.close();
        outputStream.close();
        client.close();
    }

}

2、Client2

package com.tensent.class4.client;

import com.sun.xml.internal.messaging.saaj.soap.SOAPVersionMismatchException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/27 - 04 - 27 - 9:34
 * @Description: com.tensent.class4.client
 * @version: 1.0
 */
public class Client2 {

    public static void main(String[] args) throws IOException {
        //创建Socket对象
        Socket client = new Socket("127.0.0.1",10000);
        //从socket中获取输出流
        /**************************向服务器发送一条消息*******************************/
        OutputStream outputStream = client.getOutputStream();
        outputStream.write("nihao,服务器,我是客户端!".getBytes());

        /**************************接收服务器响应的消息*******************************/
        InputStream inputStream = client.getInputStream();
        //读取服务器响应回来的数据
        byte[] buffer = new byte[1024];
        int length = inputStream.read(buffer);
        System.out.println("服务器说:" + new String(buffer,0,length));

        //关闭资源
        inputStream.close();
        outputStream.close();
        client.close();

    }
}

3、LoginClient

package com.tensent.class6.client;

import com.sun.corba.se.impl.orbutil.CorbaResourceUtil;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.omg.PortableInterceptor.INACTIVE;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 10:31
 * @Description: com.tensent.class6.client
 * @version: 1.0
 */
public class LoginClient {

    public static void main(String[] args) throws IOException {
//        //创建Socket对象
//        Socket socket = new Socket("127.0.0.1",10008);
//        //从socket中获取输出流
//        OutputStream outputStream = socket.getOutputStream();
//        //接收键盘输入的User
//        User user =getUser();
//        //使用ObjectOutputStream包装流
//        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
//        objectOutputStream.writeObject(user);
//        socket.shutdownOutput();
//
//        //接收服务器端响应的验证消息
//        InputStream inputStream = socket.getInputStream();
//        DataInputStream dataInputStream = new DataInputStream(inputStream);
//        String msg = dataInputStream.readUTF();
//        System.out.println("服务器响应消息:" + msg);
//        socket.shutdownInput();
//        //关闭资源
//        dataInputStream.close();
//        inputStream.close();
//        objectOutputStream.close();
//        outputStream.close();
//        socket.close();

        while(true){
            //创建Socket对象
            Socket socket = new Socket("127.0.0.1",10008);
            //从socket中获取输出流
            OutputStream outputStream = socket.getOutputStream();
            //接收键盘输入的User
            User user =getUser();
            //使用ObjectOutputStream包装流
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(user);
            socket.shutdownOutput();

            //接收服务器端响应的验证消息
            InputStream inputStream = socket.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            String msg = dataInputStream.readUTF();
            System.out.println("服务器响应消息:" + msg);
            socket.shutdownInput();
            //关闭资源
            dataInputStream.close();
            inputStream.close();
            objectOutputStream.close();
            outputStream.close();
        }
//        socket.close();
    }

     public static User getUser(){
         Scanner scanner = new Scanner(System.in);
         System.out.print("请输入用户名:");
         String username = scanner.next();
         System.out.print("请输入密码:");
         String pwd = scanner.next();
         User user = new User(username,pwd);
         return user;
     }
}

4、PicClient

package com.tensent.class6.client;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 10:16
 * @Description: com.tensent.class6.client
 * @version: 1.0
 */
public class PicClient {

    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("2.jpg");
        //创建Socket对象
        Socket socket = new Socket("localhost",10086);
        //从socket中获取输出流
        OutputStream outputStream = socket.getOutputStream();
        //读取文件数据写入到服务器端
        int read = 0;
        while((read = fileInputStream.read())!=-1){
            outputStream.write(read);
        }
        //截断输出流
        socket.shutdownOutput();

        //读取服务端响应的消息
        InputStream inputStream = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int length = inputStream.read(buffer);
        System.out.println("服务响应的消息:" + new String(buffer,0,length));
        socket.shutdownInput();

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

}

5、UDPClient

package com.tensent.class6.client;

import java.net.*;
import java.util.Scanner;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 11:10
 * @Description: com.tensent.class6.client
 * @version: 1.0
 */
public class UDPClient {

    public static void main(String[] args) throws Exception {
        //创建DatagramSocket对象
        DatagramSocket datagramSocket = new DatagramSocket(10001);
        //定义一个DatagramPacket数据包来封装要传输的数据
        Scanner scanner = new Scanner(System.in);
        String msg = scanner.nextLine();
        DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),msg.getBytes().length, InetAddress.getByName("DESKTOP-6S53GRB"),10086);
        //发送数据
        datagramSocket.send(datagramPacket);
        //关闭资源
        datagramSocket.close();
    }
}

5、User

package com.tensent.class6.client;

import java.io.Serializable;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/4/29 - 04 - 29 - 10:30
 * @Description: com.tensent.class6.client
 * @version: 1.0
 */
public class User implements Serializable {

    private static final long serialVersionUID = -6558683375052993939L;
    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jason的java世界

不要吝啬你的赞赏哦~~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值