經過一個多月枯燥的Java編程基礎學習,終于學到net了,呵呵.. .. ..挺好玩
上服務器端程序:
TestTCPServer package socketdemo; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class TestTCPServer { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(9999); while(true){ System.out.println("----------服務端已經啟動------------"); Socket s = ss.accept(); // System.out.println(s.getLocalPort()+" "+s.getPort()+" "+s.getLocalAddress().getHostAddress()); // System.out.println(s.getInetAddress().getHostAddress()+":"+s.getPort()+ // "客戶端已經 連接上服務器ServerSocket"); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); System.out.println("客戶端【"+s.getInetAddress().getHostAddress()+"::"+s.getPort()+"】已經連接"); dos.writeUTF("服務器端寫入客戶端的數據:客戶端【"+s.getInetAddress().getHostAddress()+"::"+s.getPort()+ "】已經連接上服務器端【"+s.getLocalAddress().getHostAddress()+"::"+s.getLocalPort()+"】!"); dos.flush(); dos.close(); s.close(); } } }
運行結果:
上客戶端程序:
TestTCPClient package socketdemo; import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; public class TestTCPClient { public static void main(String[] args)throws IOException { for(int i =0;i<5;i++){ Socket s = new Socket("192.168.0.2",9999); // ------------------------------------------ DataInputStream dis = new DataInputStream(s.getInputStream()); System.out.println("接收:"+dis.readUTF()); dis.close(); // ------------------------------------------ s.close(); } } }
運行結果:
(客戶端)
(服務器端)