BIO編程

服務端

① 創建ServerSocket對象,綁定監聽端口
② 通過accept()方法監聽客戶端請求
③ 連接建立後,通過輸入流讀取客戶端發送的請求信息
④ 通過輸出流向客戶端發送鄉音信息
⑤ 關閉相關資源

/**
 * 基於TCP協議的Socket通信,實現用戶登錄,服務端
*/
//1、創建一個服務器端Socket,即ServerSocket,指定綁定的端口,並監聽此端口
ServerSocket serverSocket =newServerSocket(10086);//1024-65535的某個端口
//2、調用accept()方法開始監聽,等待客戶端的連接
Socket socket = serverSocket.accept();
//3、獲取輸入流,並讀取客戶端信息
InputStream is = socket.getInputStream();
InputStreamReader isr =newInputStreamReader(is);
BufferedReader br =newBufferedReader(isr);
String info =null;
while((info=br.readLine())!=null){
System.out.println("我是服務器,客戶端說:"+info);
}
socket.shutdownInput();//關閉輸入流
//4、獲取輸出流,響應客戶端的請求
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.write("歡迎您!");
pw.flush();


//5、關閉資源
pw.close();
os.close();
br.close();
isr.close();
is.close();
socket.close();
serverSocket.close();

客戶端

① 創建Socket對象,指明需要連接的服務器的地址和端口號
② 連接建立後,通過輸出流想服務器端發送請求信息
③ 通過輸入流獲取服務器響應的信息
④ 關閉響應資源

//客戶端
//1、創建客戶端Socket,指定服務器地址和端口
Socket socket =newSocket("localhost",10086);
//2、獲取輸出流,向服務器端發送信息
OutputStream os = socket.getOutputStream();//字節輸出流
PrintWriter pw =newPrintWriter(os);//將輸出流包裝成打印流
pw.write("用戶名:admin;密碼:123");
pw.flush();
socket.shutdownOutput();
//3、獲取輸入流,並讀取服務器端的響應信息
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = null;
while((info=br.readLine())!null){
 System.out.println("我是客戶端,服務器說:"+info);
}

//4、關閉資源
br.close();
is.close();
pw.close();
os.close();
socket.close();

多線程

1、創建一個ServerSocket實例並指定本地端口,用來監聽客戶端在該端口發送的TCP連接請求;
2、重複執行:
1)調用ServerSocket的accept()方法以獲取客戶端連接,並通過其返回值創建一個Socket實例;
2)爲返回的Socket實例開啓新的線程,並使用返回的Socket實例的I/O流與客戶端通信;
3)通信完成後,使用Socket類的close()方法關閉該客戶端的套接字連接。

//服務器線程處理
//和本線程相關的socket
Socket socket =null;
//
public serverThread(Socket socket){
this.socket = socket;
}

publicvoid run(){
//服務器處理代碼
}

//============================================
//服務器代碼
ServerSocket serverSocket =newServerSocket(10086);
Socket socket =null;
int count =0;//記錄客戶端的數量
while(true){
socket = serverScoket.accept();
ServerThread serverThread =newServerThread(socket);
 serverThread.start();
 count++;
System.out.println("客戶端連接的數量:"+count);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章