多線程實現服務器與多個客戶端通信

鑑於ServerSocket的accept方法是阻塞的,那麼只能通過多線程的方式實現多客戶端連接與服務器連接

基本步驟:

1,服務端創建ServerSocket綁定端口號,循環調用accept()方法

2,客戶端創建一個socket並請求和服務器端連接

3,服務器端接受客戶端請求,創建socket與該客戶建立連接

4,兩個socket在一個單獨的線程上通話

5,服務器端繼續等待新的連接

也就是說當有一個新的客戶端與服務端連接,就創建一個新的socket並在這個線程裏面通信。

服務端代碼:

multithreadingServer.class:

public class multithreadingServer {
  public static void main(String[] args) {
	  try {
		ServerSocket serversocket=new ServerSocket(8888);
		Socket socket=null;
		int n=0;
		while(true){
				socket=serversocket.accept();//再來一個客戶端就新建一個socket
				ServerThread serverthread=new ServerThread(socket);
				serverthread.start();
				n++;
				System.out.println("已有"+n+"臺客戶端連接");
			    InetAddress address=socket.getInetAddress();//獲取客戶端的inetaddress對象
			    System.out.println("當前主機ip:"+address.getHostAddress());//獲取客戶端的ip
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
}
}
ServerThread.class:

public class ServerThread extends Thread{//服務器線程處理類
 Socket socket=null;
 InputStream is=null;
 BufferedReader br=null;
 OutputStream os=null;
 PrintWriter pw=null;
  public ServerThread(Socket socket){
	 this.socket=socket;
 }
  public void run(){
	  try {
		    is=socket.getInputStream();//獲得字節流
			br=new BufferedReader(new InputStreamReader(is));//字節流轉化爲字符流並添加緩衝
			String info=null;
			while((info=br.readLine())!=null){
				System.out.println("我是服務端,客戶端說:"+info);
			}
			socket.shutdownInput();//必須要及時關閉,因爲readline這個方法是以\r\n作爲界定符的,由於發送消息的那一端用的是PrintWriter的write()方法,這個方法並沒加上\r\n,所以會一直等待
			//回覆客戶端
			os=socket.getOutputStream();
		    pw=new PrintWriter(os);
			pw.write("歡迎您!");
			pw.flush();
			
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally{
		if (pw!=null)
		pw.close();
		try {
			if (os!=null)
			os.close();
			if (br!=null)
			br.close();
			if (is!=null)
			is.close();//關閉返回的 InputStream 將關閉關聯套接字。 
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
  }
}

客戶端代碼保持不變:

public class client {
	public static void main(String[] args) {
		try {
			Socket socket=new Socket("127.0.0.1",8888);//創建客戶端socket,因爲是本地,ip地址就是127.0.0.1
			OutputStream os=socket.getOutputStream();
			PrintWriter pw=new PrintWriter(os);
			pw.write("用戶名:admin;密碼:123");
			pw.flush();
			socket.shutdownOutput();//必須加上這句話,表示輸出流的結束,注意此時不能關閉os,因爲關閉os會關閉綁定的socket
			//在客戶端獲取迴應信息
			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();
		}
	}

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章