基于bio实现socket网络编程 (字符流和长连接)

客户端:

package com.demo1;

import com.util.StreamUtil;
import lombok.extern.slf4j.Slf4j;

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

/**
 * Created by syd on 2019/6/26.
 */
@Slf4j
public class Client {

    public static void main(String[] args) {
        BufferedReader br = null;
        BufferedReader key = null;
        PrintWriter pw = null;
        String cmd;
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 7707);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            pw = new PrintWriter(socket.getOutputStream(), true);
            System.out.println("say bye to exit");
            key = new BufferedReader(new InputStreamReader(System.in));
            while ((cmd = key.readLine()) != null) {
                pw.println(cmd);
                String s = br.readLine();
                System.out.println(String.format("server say %s", s));
                if ("bye".equalsIgnoreCase(s)) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StreamUtil.close(br);
            StreamUtil.close(key);
            StreamUtil.close(pw);
            StreamUtil.close(socket);
        }
        System.out.println("bye");
    }

}

服务端:

package com.demo1;

import com.util.StreamUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by syd on 2019/6/26.
 */
@Slf4j
public class Server implements Runnable {

    private static ThreadPoolExecutor pool;
    private ServerSocket serverSocket = null;
    static {
        int processors = Runtime.getRuntime().availableProcessors();
        pool = new ThreadPoolExecutor(processors * 2, processors * 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue ());
    }

    public void start() throws IOException {
        serverSocket = new ServerSocket(7707);
        pool.execute(this);
    }

    @Override
    public void run() {
        Socket socket;
        try {
            // accept 方法会一直阻塞,直到新的连接请求进来
            while ((socket = serverSocket.accept()) != null) {
                log.info("client {} connected", socket.getRemoteSocketAddress());
                pool.execute(new Processor(socket));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        // 关闭serverSocket和线程池
        if (serverSocket != null &&!serverSocket.isClosed()) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        pool.shutdown();
    }

    public static void main(String[] args) {
        Server server = new Server();
        BufferedReader br = null;
        try {
            server.start();
            System.out.println("Enter exit to exit");
            br = new BufferedReader(new InputStreamReader(System.in));
            String cmd;
            while ((cmd = br.readLine()) != null) {
                if ("exit".equalsIgnoreCase(cmd)) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StreamUtil.close(br);
            server.close();
        }
    }

}


package com.demo1;

import com.util.StreamUtil;
import lombok.extern.slf4j.Slf4j;

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

/**
 * Created by syd on 2019/6/26.
 */
@Slf4j
public class Processor implements Runnable {

    private Socket socket;

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

    @Override
    public void run() {
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            pw = new PrintWriter(socket.getOutputStream(), true);
            // 通过socket读写字符串,收到客户端发送的 bye 后退出
            while (!Thread.interrupted()) {
                String s = br.readLine();
                System.out.println(String.format("%s say %s", socket.getRemoteSocketAddress(), s));
                pw.println("server: " + s);
                if ("bye".equalsIgnoreCase(s)) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StreamUtil.close(pw);
            StreamUtil.close(br);
            StreamUtil.close(socket);
        }
    }

}

工具类:

package com.util;

import lombok.extern.slf4j.Slf4j;

import java.io.Closeable;

/**
 * Created by syd on 2019/6/26.
 */
@Slf4j
public class StreamUtil {

    public static void close (Closeable source) {
        if (source == null) {
            return;
        }
        try {
            source.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("error on close {}", source.getClass().getName());
        }
    }

}

 

你可能感兴趣的:(学习)