## 多線程服務器
應用多線程實現服務器與多客戶端之間的通信
### 基本步驟
1. 服務器端創建ServerSocket,循環調用accept()等待客戶端連接
2. 客戶端創建一個socket并請求和服務器端連接
3. 服務器端接受客戶端請求,創建socket與該客戶建立專線連接
4. 建立連接的兩個socket在一個單獨的線程上對話
5. 服務器端矩形等待新的連接
### 實現實例代碼
通過多線程處理多個連接
~~~java
/*
* 服務器線程處理類
*/
public class ServerThread extends Thread {
// 和本線程相關的Socket
Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
// 線程執行的操作,響應客戶端的請求
public void run() {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
try {
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String info = null;
while ((info = br.readLine()) != null) {
// 循環讀取客戶端的信息
System.out.println("我是服務器,客戶端說:" + info);
}
socket.shutdownInput();// 關閉輸入流
// 獲取輸出流,響應客戶端的請求
os = socket.getOutputStream();
pw = new PrintWriter(os);
pw.write("歡迎你");
pw.flush();// 調用flush()方法將緩沖輸出
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉資源
try {
if (pw != null) {
pw.close();
}
if (os != null) {
os.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (is != null) {
is.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
~~~
---
服務器循環監聽
~~~java
public class Server {
/**
* 基于TCP協議的Socket通信,實現用戶登陸 服務器端
* @param args
*/
public static void main(String[] args) {
try {
// 1.創建一個服務器端Socket,即ServerSocket,指定綁定的端口,并監聽此端口
ServerSocket serverSocket = new ServerSocket(8886);
Socket socket = null;
// 記錄客戶端的數量
int count = 0;
System.out.println("***服務器啟動***");
// 循環監聽客戶端的連接
while (true) {
socket = serverSocket.accept();
// 創建一個新的線程
ServerThread serverThread = new ServerThread(socket);
// 啟動線程
serverThread.start();
count++;
System.out.println("客戶端數量:" + count);
InetAddress address = socket.getInetAddress();
System.out.println("當前客戶端的IP:" + address.getHostAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~~
---
客戶端代碼
~~~java
public class Client {
/**客戶端
* @param args
*/
public static void main(String[] args) {
try {
//1、創建客戶端Socket,指定服務器地址和端口
Socket socket = new Socket("localhost",8886);
//2、獲取輸出流,向服務端發送信息
OutputStream os = socket.getOutputStream();//字節輸出流
PrintWriter pw = new PrintWriter(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();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~~