欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java后端笔记15

程序员文章站 2022-05-12 22:21:38
...

网络编程

三要素:协议、IP地址、端口号

TCP

TCP是一个面向连接的通信协议,需要完成“三次握手”才能通信
Java后端笔记15
套接字socket使用

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

/**
 * Create by xiye on 2019/12/6 14:40
 */
public class Server {
    /*
    * 服务端使用ServerSocket
    * */
    public static void main(String[] args) throws IOException {   
        // 设置一个监听端口,供客户端访问
        ServerSocket socket = new ServerSocket(1314);
        System.out.println("服务已开启...");

        Socket server = socket.accept();        // 阻塞,等待客户端接收
        String host = getHost(server);

        // 获取客户端请求内容
        InputStream is = server.getInputStream();
        byte[] b = new byte[128];
        int len = is.read(b);
        String req = new String(b, 0, len);
        System.out.println(host + ":" + req);
        // 返回信息
        OutputStream os = server.getOutputStream();
        os.write(req.getBytes());

        os.close();
        is.close();
        server.close();
    }

    /**
     * 获取IP地址和端口号拼接字符串
     * @param socket 套接字对象
     * @return IP地址:端口
     */
    private static String getHost(Socket socket) {
        return socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
    }
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * Create by xiye on 2019/12/6 14:43
 */
public class Client {
    /*
    * 客户端使用Socket
    * */
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        // 连接服务端IP和端口
        Socket client = new Socket("192.168.31.103", 1314);

        // String str = "Nice to meet you~^_^~";
        String str = sc.next();
        OutputStream os = client.getOutputStream();
        // 发送
        os.write(str.getBytes());
        // 接收回返消息
        InputStream is = client.getInputStream();
        if (is != null) {
            String host = getHost(client);
            byte[] b = new byte[128];
            int len = is.read(b);
            System.out.print(host + "回复您:" + new String(b, 0, len));
        }
        is.close();
        os.close();

        client.close();
        sc.close();
    }

    /**
     * 获取IP地址和端口号拼接字符串
     * @param socket 套接字对象
     * @return IP地址:端口
     */
    private static String getHost(Socket socket) {
        return socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
    }
}

TCP单一聊天实现
服务端

package com.xiye.single;

import com.xiye.single.thread.Receive;
import com.xiye.single.thread.Send;

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

/**
 * Create by xiye on 2019/12/6 16:42
 */
public class ServerTCP {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(1314);
        System.out.println("服务端开启....");

        Socket socket = serverSocket.accept();
        new Thread(new Receive(socket)).start();
        new Thread(new Send(socket)).start();
    }
}

客户端

package com.xiye.single;

import com.xiye.single.thread.Receive;
import com.xiye.single.thread.Send;

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

/**
 * Create by xiye on 2019/12/6 16:42
 */
public class ClientTCP {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("192.168.31.103", 1314);

        new Thread(new Receive(socket)).start();
        new Thread(new Send(socket)).start();
    }
}

发送线程

package com.xiye.single.thread;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * Create by xiye on 2019/12/6 16:42
 */
public class Send implements Runnable {

    private Socket socket;

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

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (socket != null) {
                    Scanner sc = new Scanner(System.in);
                    System.out.print("聊天内容:");
                    try {
                        OutputStream os = socket.getOutputStream();
                        os.write(sc.nextLine().getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private static String getHost(Socket socket) {
        return socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
    }
}

接收线程

package com.xiye.single.thread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * Create by xiye on 2019/12/6 16:42
 */
public class Receive implements Runnable {

    private Socket socket;

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

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (socket != null) {
                    try {
                        InputStream is = socket.getInputStream();
                        byte[] bytes = new byte[256];
                        int len = is.read(bytes);

                        System.out.println("收到" + getHost(socket) + "信息:" + new String(bytes, 0, len));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private static String getHost(Socket socket) {
        return socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
    }
}

UDP

  • UDP是一个面向无连接的通信协议,不安全,容易丢包
package com.xiye.single;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;

/**
 * Create by xiye on 2019/12/6 18:31
 */
public class ServerUDP {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(1314);
        while (true) {
            byte[] bytes = new byte[256];
            // 获取客户端请求信息
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
            socket.receive(packet);         // 阻塞
            System.out.println(new String(packet.getData(), 0, packet.getLength()));

            // 返回信息
            byte[] b = new byte[packet.getLength()];
            System.arraycopy(packet.getData(), 0, b, 0, packet.getLength());

            System.out.println(getHost(packet) + ":" + Arrays.toString(b));

            packet.setData(b);
            socket.send(packet);
        }
    }
    private static String getHost(DatagramPacket packet) {
        return packet.getAddress().getHostAddress() + ":" + packet.getPort();
    }
}
package com.xiye.single;

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

/**
 * Create by xiye on 2019/12/6 18:31
 */
public class ClientUDP {
    public static void main(String[] args) throws IOException {

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    new ClientUDP();
                    //Thread.sleep(500);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    public ClientUDP() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        byte[] bytes = "使用UDP数据包传输".getBytes();

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("192.168.31.103"), 1314);
        socket.send(packet);

        // 获取回返信息
        byte[] b = new byte[packet.getLength()];
        DatagramPacket dp = new DatagramPacket(packet.getData(), packet.getLength());
        socket.receive(dp);
        System.out.println("收到" + getHost(dp) + "返回信息:" + new String(dp.getData(), 0, dp.getLength()));
    }

    private static String getHost(DatagramPacket packet) {
        return packet.getAddress().getHostAddress() + ":" + packet.getPort();
    }
}
相关标签: Java笔记

上一篇: tiltShift.js

下一篇: Java后端笔记13