美文网首页
Java socket点对点异步通信

Java socket点对点异步通信

作者: 吹奏一池春水 | 来源:发表于2020-01-16 10:13 被阅读0次

服务端代码

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SocketServer {

    private ServerSocket server;
    private Socket socket;
    private final AtomicInteger threadNum = new AtomicInteger();

    public SocketServer(int port) throws IOException {
        server = new ServerSocket(port, 1);
    }

    public void start() {
        // 服务的线程池执行避免每次连接创建新线程
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2,
                0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
        while (true) {
            // 当前连接读写线程未释放前不处理新的连接
            while (threadNum.get() > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("waiting connection...");
            try {
                socket = server.accept();
                System.out.println("connect success from " + socket.getRemoteSocketAddress());

                threadNum.addAndGet(2);
                threadPoolExecutor.execute(new ReadThread());
                threadPoolExecutor.execute(new WriteThread());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void close() {
        if (!socket.isClosed()) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取客户端消息线程
     */
    class ReadThread implements Runnable {
        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int length;
                while ((length = inputStream.read(bytes)) != -1) {
                    String message = new String(bytes, 0, length, StandardCharsets.UTF_8);
                    System.out.println(socket.getRemoteSocketAddress() + " client message: " + message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                close();
                System.out.println("ReadThread close");
                threadNum.decrementAndGet();
            }
        }
    }

    /**
     * 发送消息线程
     */
    class WriteThread implements Runnable {
        @Override
        public void run() {
            try {
                OutputStream outputStream = socket.getOutputStream();
                Scanner scanner = new Scanner(System.in);
                String message = null;
                while (!"q".equals(message) && scanner.hasNextLine()) {
                    message = scanner.nextLine();
                    outputStream.write(message.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                    System.out.println("push: " + message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                close();
                System.out.println("WriteThread close");
                threadNum.decrementAndGet();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new SocketServer(23333).start();
    }
}

客户端代码

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class SocketClient {

    private Socket socket;

    public SocketClient(String host, int port) throws IOException {
        socket = new Socket(host, port);
        System.out.println("connect success to " + socket.getRemoteSocketAddress());
    }

    public void start() {
        new ReadThread().start();
        new WriteThread().start();
    }

    public void close() {
        if (!socket.isClosed()) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取服务端消息线程
     */
    class ReadThread extends Thread {
        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int length;
                while ((length = inputStream.read(bytes)) != -1) {
                    String message = new String(bytes, 0, length, StandardCharsets.UTF_8);
                    System.out.println("server message: " + message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                close();
                System.out.println("ReadThread close");
            }
        }
    }

    /**
     * 发送消息线程
     */
    class WriteThread extends Thread {
        @Override
        public void run() {
            try {
                OutputStream outputStream = socket.getOutputStream();
                Scanner scanner = new Scanner(System.in);
                String message = null;
                while (!"q".equals(message) && scanner.hasNextLine()) {
                    message = scanner.nextLine();
                    outputStream.write(message.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                    System.out.println("push: " + message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                close();
                System.out.println("WriteThread close");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new SocketClient("127.0.0.1", 23333).start();
    }
}

运行效果

1、先启动服务端



2、再启动客户端



3、互相发送消息

相关文章

  • Java socket点对点异步通信

    服务端代码 客户端代码 运行效果 1、先启动服务端 2、再启动客户端

  • Java socket

    Java Socket实现基于TCP和UDP多线程通信Java Socket编程

  • Socket 通信 知识梳理

    1.socket是网络通信的一项技术,android的socket通信其实使用的是java的socket通信技术。...

  • 一、项目分析

    点对点的通信 采用C/S模型 客户端使用Qt实现 linux + socket 一、功能模型

  • Java socket应用—通信

    ** |Java socket应用—通信|** 1、网络基础简介 ...

  • 基于TCP的Socket网络编程基础(Java)

    Socket通信作为Java网络通讯的基础内容,建立网络通信连接至少要一对端口号(socket)。socket本...

  • Android中Socket编程(一)

    Socket通信简介 Java Socket可实现客户端-服务端的双向实时通信。在java.net包中定义了两个类...

  • 1.普通Socket的用法

    Java中网络通信是通过Socket实现的。Socket分为ServerSocket和Socket两大类。Serv...

  • java socket通信

    socket通信是通信的一种,有客户端和服务器端 服务器端是一个阻塞的状态,在死循环中,如果没有连接就会一直阻塞....

  • Java Socket通信

    目标 Demo是通过Java ServerSocket 和 Socket 通信实现客户端发送消息和发送文件到服务器...

网友评论

      本文标题:Java socket点对点异步通信

      本文链接:https://www.haomeiwen.com/subject/nhqfzctx.html