首页 > 编程语言 > 详细

多线程实现多客户端连接服务器

时间:2019-05-07 13:32:51      阅读:128      评论:0      收藏:0      [点我收藏+]
public class ServerThread extends Thread{
    Socket socket = null;
    public ServerThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String info = null;
        while ((info=br.readLine())!=null) {
            System.out.println("我是服务器,客户端说" + info);
        }
        socket.shutdownInput();
        OutputStream os = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(os);
        pw.write("欢迎您");
        pw.flush();    
        pw.close();
        os.close();
        br.close();
        isr.close();
        is.close();
        socket.close();
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    }
}
public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost",8888);
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.write("用户名:tom;密码:123");
            pw.flush();
            socket.shutdownOutput();
            
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String info = null;
            while ((info=br.readLine())!=null) {
                System.out.println("我是客户端,服务器说" + info);
            }
            br.close();
            is.close();
            pw.close();
            os.close();
            socket.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
public class Server {
    public static void main(String[] args) {
        int count =0;
        try {
            ServerSocket serverSocket =  new ServerSocket(8888);
            System.out.println("服务器即将启动,等待客户端的连接");
            Socket socket = null;
            while (true) {
                count++;
                socket = serverSocket.accept();
                ServerThread serverThread = new ServerThread(socket);
                serverThread.start();
                System.out.println(count);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

多线程实现多客户端连接服务器

原文:https://www.cnblogs.com/dulute/p/10824837.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!