實現服務端與客戶端簡單的通信;
package 網絡編程; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); try { @SuppressWarnings("resource") ServerSocket server = new ServerSocket(9880); while (true){ Socket client = server.accept(); System.out.println("來自"+ client.getInetAddress().getHostAddress()+"的客戶端已連接成功!"); if(client != null){ //開始對話 OutputStream os = client.getOutputStream();//從 client 獲取一個輸出字節流 PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os))); System.out.print("我說:"); String serverMsg = input.nextLine(); pw.println(serverMsg); //發送 serverMsg 給客戶端 pw.flush(); //服務端讀取客戶端發送來的信息 InputStream is = client.getInputStream(); //獲取來自 客戶端的字節流 //讀取字節流(字節流轉換成字符流)帶緩沖 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String msg = reader.readLine(); //每次讀取一行信息 System.out.print("客戶端說:"+msg); } } } catch (IOException e) { e.printStackTrace(); } input.close(); } }
package 網絡編程; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class Client1 { public static void main(String[] args) { @SuppressWarnings("resource") Scanner input = new Scanner(System.in); try { @SuppressWarnings("resource") Socket client = new Socket("127.0.0.1",9880); //通過socket獲得輸入流 InputStream is = client.getInputStream();
//將輸入字節流轉換成字符流並緩沖 BufferedReader reader= new BufferedReader(new InputStreamReader(is)); //讀取輸入流 String msg = reader.readLine(); //打印來自服務端的信息 System.out.println("服務端說:"+msg); //向服務端發送消息 System.out.print("我說:");
//輸入要向服務端發送的信息 String clientMsg = input.nextLine(); //獲得輸出字節流 OutputStream os = client.getOutputStream();//
//將輸出字節流轉換為字節流加緩沖(緩沖後的為字符流)寫入打印流 PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os))); pw.println(clientMsg); //將打印流裡的文本信息發送 clientMsg 給服務端 pw.flush(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Output: