Java socket点对点异步通信

服务端代码

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、互相发送消息

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 7.2 面向套接字编程我们已经通过了解Socket的接口,知其所以然,下面我们就将通过具体的案例,来熟悉Socke...
    lucas777阅读 1,208评论 0 2
  • 一. Java基础部分.................................................
    wy_sure阅读 3,854评论 0 11
  • 桥外四首 闲不语 之一桥 人间的了悲欢就像无边的水离不开岁月的岸 岁月的岸无声地举起一个个黑白相间的日子 在岸与岸...
    闲不语阅读 113评论 0 2
  • 很快,复习的进度快赶上学习的进度了,按照艾宾浩斯记忆曲线定时回顾,反思践行过程。早睡、早起、养生、运动、...
    yolanda的花花世界阅读 100评论 0 1
  • es6新推出了let const块级元素与之前的var的主要区别以下几点 let全局变量不再是window 块级作...
    带带带前端阅读 245评论 0 0