應用多線程來實現服務器與多客戶端之間的通信。
基本步驟:
1.服務器端創建ServerSocket,循環調用accept()等待客戶端的連接
2.客戶端創建一個socket並請求和服務器端的連接
3.服務器端接收客戶端的請求,創建socket與該客戶端建立專線連接
4.建立連接的兩個socket在一個單獨的線程上對話
5.服務器端繼續等待新的客戶端的連接
Server.java
public class Server {
public static void main(String[] args) throws IOException{
//1、創建一個服務器端的socket,指定綁定的端口,並偵聽此端口
ServerSocket server = new ServerSocket(8888);
System.out.println("********服務端即將啟動,等待客戶端的連接********");
int count = 0;
//2、開始偵聽,等待客戶端的連接
while(true){
Socket socket = server.accept();
ServerThread thread = new ServerThread(socket);
thread.start();
count++;
System.out.println("客戶端的數量:"+count);
InetAddress address = socket.getInetAddress();
System.out.println("客戶端的ip:"+address.getHostAddress());
}
}
}
ServerThread.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 {
//3、獲取輸入流,用來讀取客戶端發送的信息
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();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
//4、關閉資源
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();
}
}
}
}
Client.java
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException{
//1、創建客戶端socket,指定服務器地址和端口
Socket socket = new Socket("127.0.0.1",8888);
System.out.println("******客戶端已准備就緒*******");
//2、給服務端發送數據
OutputStream os = socket.getOutputStream();//字節流
PrintWriter pw = new PrintWriter(os);//打印流
pw.write("用戶名:admin;密碼:123456");
pw.flush();
socket.shutdownOutput();//關閉輸出流
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();//關閉輸入流
//3、關閉資源
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
}
}