BIo实现简单聊天系统

该博客介绍了使用Java实现的基于BIO( Blocking Input/Output)模型的简单TCP服务器和客户端。客户端通过自定义的线程池`TimeServerHandlerExecutorPool`来处理接收到的服务器响应,并进行多线程处理。服务器端监听9092端口,接收客户端连接,并同样使用线程池处理请求。示例展示了如何在Java中进行网络编程以及基础的并发处理。
摘要由CSDN通过智能技术生成

 

1.client端

package BioServer;

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

/**
 * Created by lwj32 on 2021/3/17.
 */
public class BioClient {
    private static final TimeServerHandlerExecutorPool timeServerHandlerExecutorPool = new TimeServerHandlerExecutorPool(100, 100);

    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            socket = new Socket("127.0.0.1", 9092);
            //循环读
            timeServerHandlerExecutorPool.execute(new BioClientHandler(socket));
            outputStream = socket.getOutputStream();
            Scanner scanner = new Scanner(System.in);
            System.out.println(" 请输入要发送的数据");
            while (true) {
                String s = scanner.nextLine();
                if (s.trim().equals("by")) {
                    break;
                }
                outputStream.write(s.getBytes());
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

1.1拦截器开多线程处理来的请求

package BioServer;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * Created by lwj32 on 2021/3/22.
 */

public class BioClientHandler  implements Runnable{

    private Socket socket;
    public BioClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream in = null;
        try {
            in = socket.getInputStream();
            int count = 0;
            byte[] bytes = new byte[1024];
            while ((count=in.read(bytes))!=-1){
                System.out.println("\n收到服务器消息:  "+new String(bytes,0,count,"utf-8"));
                System.out.print("请输入要发送的消息:");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

2、Server端

package BioServer;

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

/**
 * Created by lwj32 on 2021/3/22.
 */
public class BioServer {
    ServerSocket serverSocket = null;
    TimeServerHandlerExecutorPool timeServerHandlerExecutorPool = new TimeServerHandlerExecutorPool(100,100);
    private BioServer() {

        try {
            serverSocket = new ServerSocket(9092);
            while (true){
                //阻塞
                Socket scoket = serverSocket.accept();
                System.out.println("客户端连接来了 "+ scoket.getRemoteSocketAddress().toString() );
              //  new Thread(new BioServerHandler(scoket)).start();
                timeServerHandlerExecutorPool.execute(new BioServerHandler(scoket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args) {
        BioServer bioServer = new BioServer();
    }
}

2.1拦截器开多线程处理来的请求

package BioServer;/**
 * Created by lwj32 on 2021/3/22.
 */

import javafx.application.Application;
import javafx.stage.Stage;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BioServerHandler implements Runnable {

    private Socket socket;

    public BioServerHandler(Socket scoket) {
        this.socket = scoket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            int count = 0;
            String content = null;
            byte[] bytes = new byte[1024];
            while ((count = inputStream.read(bytes)) != -1) {
                String s = new String(bytes, 0, count, "utf-8");
                System.out.println("s = " + s);
                content = s.trim().equalsIgnoreCase("SJ") ? new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) : "你发的啥?";
                outputStream.write(content.getBytes());
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

 

3、自定义线程池

package BioServer;

import java.util.concurrent.*;

/**
 * @author lwj32
 */
public class TimeServerHandlerExecutorPool implements Executor {
    private ExecutorService executorService;
    public TimeServerHandlerExecutorPool(int queueSize, int maxSize) {
        this.executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maxSize, 1000L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize));
    }

    public TimeServerHandlerExecutorPool(int coreSize, int queueSize, int maxSize) {
        this.executorService = new ThreadPoolExecutor(coreSize, maxSize, 1000L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize));
    }

    @Override
    public void execute(Runnable command) {
        executorService.execute(command);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值