1. 程式人生 > >多線程實現多客戶端連接服務器

多線程實現多客戶端連接服務器

buffere ring local start string info trac buffered amr

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();
        }
    }
}

多線程實現多客戶端連接服務器