Socket 实现简单的多线程服务器程序

**********服务器端*************

public class ServerSocket{

    public static void main(String[] args) throws Exception {
         try{
             ServerSocket ss=new ServerSocket(8888);
             System.out.println("启动服务器...");
             //记录客户端的链接数量
             int count=0;
             //循环侦听等待客户端的链接
             while(true){
                //侦听并接受到此套接字的连接。
                 Socket s=ss.accept();
                //创建一个线程
                 ServerThread mt=new ServerThread(s);
                 mt.start();
                 count++;
                 System.out.println("客户端的连接数量:"+count);
                 System.out.println("客户端:"+s.getInetAddress().getHostName()+"已连接到服务器");
             }
         }catch(IOException e){
             e.printStackTrace();
            
         }
    }
}

class ServerThread extends Thread {
    Socket s=null;
    public ServerThread(Socket s){
        this.s=s;
    }
    
    public void run(){
        BufferedReader br=null;
        BufferedWriter bw=null;
        try{
            //读取服务器的输入流,也就是从客户端来的消息
             br=new BufferedReader(new InputStreamReader(s.getInputStream()));
             //读取客户端发送来的消息
             String mess=br.readLine();
             System.out.println("客户端:"+mess);
             //服务器的输出流,也就是向客户端返回的消息
             bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
             bw.write("您已成功链接服务器"+"\n");
             bw.flush();
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
}

 

**************客户端*********************

public class Client{

    public static void main(String[] args) {
        try {
            Socket s=new Socket("127.0.0.1", 8888);
            
            //读取服务器返回的消息
            BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
            String mess=br.readLine();
            System.out.println("服务器:"+mess);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

posted @ 2017-11-29 21:38  Downtime  阅读(344)  评论(0编辑  收藏  举报
TOP