一、服務器端
1、創建serverSocket,即服務器端的socket,綁定指定的端口,並偵聽此端口
ServerSocket server = new ServerSocket(8888);
2、調用accept()方法,開始偵聽,等待客戶端的連接,在未連接成功之前,處於阻塞狀態,返回的socket,用於與客戶端連接
Socket socket = server.accept();
3、獲取輸入流,用來讀取客戶端發來的信息
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();//關閉輸入流
4、獲取輸出流,用戶響應客戶端的請求
OutputStream os = socket.getOutputStream();//字節輸出流
PrintWriter pw = new PrintWriter(os);//打印輸出流
pw.write("服務器端已接受你的請求,允許登錄");
pw.flush();
socket.shutdownOutput();//關閉輸出流
5、關閉資源
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
server.close();
二、客戶端
1、創建客戶端socket,指定要連接的服務器地址和端口號
Socket socket = new Socket("127.0.0.1",8888);
2、獲取輸出流,給服務器端發送信息
OutputStream os = socket.getOutputStream();//字節流
PrintWriter pw = new PrintWriter(os);//打印流
pw.write("用戶名:admin;密碼:123");
pw.flush();
socket.shutdownOutput();//關閉輸出流
3、獲取輸入流,用來讀取服務器端發來的信息
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();//關閉輸入流
4、關閉資源
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();