首页 > 代码库 > JAVA BIO 服务器与客户端实现示例

JAVA BIO 服务器与客户端实现示例

代码只兼容JAVA 7及以上版本。


服务器端代码:

package com.stevex.app.bio;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
import javax.net.ServerSocketFactory;
 
public class XiaoNa {
    public static void main(String[] args){
        XiaoNa xiaona = new XiaoNa();
         
        ServerSocket serverSocket = null;
        Socket socket = null;
 
        try {
            //可以设置客户连接请求队列的长度,比如5,队列长度超过5后拒绝连接请求
            //serverSocket = ServerSocketFactory.getDefault().createServerSocket(8383, 5);      
            serverSocket = ServerSocketFactory.getDefault().createServerSocket(8383);
             
            while(true){
                try{
                    //监听直到接受连接后返回一个新Socket对象
                    socket = serverSocket.accept();//阻塞
                    //new一个线程处理连接请求
                    new Thread(xiaona.new Worker(socket)).start();;
                }
                catch (Throwable e) {    //防止发生异常搞死服务器          
                    e.printStackTrace();
                }              
            }          
        } catch (IOException e) {              
            e.printStackTrace();
        }
        finally{               
            try {             
                if(socket != null){
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }  
        }
    }
     
    private static String getAnswer(String question){
        String answer = null;
         
        switch(question){
        case "who":
            answer = "我是小娜";
            break;
        case "what":
            answer = "我是来帮你解闷的";
            break;
        case "where":
            answer = "我来自外太空";
            break;
        default:
                answer = "请输入 who, 或者what, 或者where";
        }
         
        return answer;
    }
     
    private class Worker implements Runnable{
        private Socket socket;
         
        public Worker(Socket socket){
            this.socket = socket;
        }
         
        @Override
        public void run() {
            BufferedReader reader = null;
            PrintWriter writer = null;
             
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             
                writer = new PrintWriter(socket.getOutputStream());
                 
                String question = reader.readLine();//没有内容会阻塞
                 
                while(!question.equals("OVER")){
                    String answer = getAnswer(question);
                    writer.println(answer);
                    question = reader.readLine();
                }
                 
                writer.println("OVER");//OVER作为操作完成暗号
                writer.flush();
                 
                if(writer != null){
                    writer.close();
                }
                                     
                if(reader != null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
         
    }
}
客户段代码:

package com.stevex.app.bio;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
 
public class Client {
    public static void main(String[] args) {
        Client c = new Client();
         
        //种20个线程发起Socket客户端连接请求
        for(int i=0; i<20; i++){
            new Thread(c.new Worker()).start();
        }      
    }
     
    private class Worker implements Runnable{
 
        @Override
        public void run() {
            Socket socket = null;
            BufferedReader reader = null;
            PrintWriter writer = null;
 
            try {
                //创建一个Socket并连接到指定的目标服务器
                socket = new Socket("localhost", 8383);
 
                reader = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                writer = new PrintWriter(socket.getOutputStream());
 
                writer.println("who");
                writer.println("what");
                writer.println("where");
                writer.println("OVER");//OVER作为操作完成暗号
                writer.flush();
 
                String answer = reader.readLine();   //没有内容会阻塞      
                while(! answer.equals("OVER")){               
                    System.out.println(Thread.currentThread().getId() + "---Message from server:" + answer);
                    answer = reader.readLine();
                }
 
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
 
                    if (reader != null) {
                        reader.close();
                    }
 
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
         
    }
}


欢迎大家访问我的个人网站 萌萌的IT人

JAVA BIO 服务器与客户端实现示例