BIO处理模型

为了提升服务器端的处理性能,则可以利用多线程的来处理多个客户端的通讯需求
BIO处理模型_第1张图片
范例:修改服务器端实现

package com.lxh.nineteenchapter;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServerBIO {
     
        private static class ClientThread implements Runnable{
        //客户端线程类
                private Socket client;  //客户端Socket
                private Scanner scan=null;   //输入流
                private PrintStream out =null;  //输出流
                private boolean flag=true;  //循环标记
                public ClientThread(Socket client) throws Exception{
     //接收客户端Socket
                	this.client=client;   //保存Socket
                	this.scan=new Scanner(client.getInputStream());// 输入流
                	this.scan.useDelimiter("\n");   //设置分隔符
                	this.out=new PrintStream(client.getOutputStream());  //输出流
                }
                
			@Override
			public void run() {
                      //线程执行
				while (this.flag) {
     
					if(scan.hasNext()) {
     
						String val=scan.next().trim();
						if("byebye".equalsIgnoreCase(val)) {
         //结束标记
							out.println("ByeBye....");     //回应信息
							this.flag=false;                     //结束循环
						}else {
     
							out.println("【Echo】"+val);
						}
					}
					
				}
				
				try {
     
					scan.close();
					out.close();
					client.close();
				} catch (IOException e) {
     
					e.printStackTrace();
				}
				
			}
        	
        }
        public static void main(String[] args) throws Exception {
     
			ServerSocket server=new ServerSocket(9998);//设置服务器监听端口
		    System.out.println("等待客户端连接......");
		    boolean flag=true;
		    while(flag) {
     
		    	Socket client=server.accept();
		    	new Thread(new ClientThread(client)).start();
		    }
		    server.close();
        }
}

执行结果

等待客户端连接......

你可能感兴趣的:(Java,se)