客戶端:MyClient package socketdemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class MyClient { Socket client; PrintWriter pw; public MyClient() throws UnknownHostException, IOException{ client=new Socket("10.241.143.54",7777); //第一個參數(shù)是做服務(wù)器端的電腦ipv4,dis下敲 ipconfig可以查看,第二個參數(shù)是端口,///客戶端和服務(wù)器端一致 pw=new PrintWriter(client.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); while(true) { System.out.println("請輸入信息:"); if(client.isClosed()) { client=new Socket("10.241.143.54", 7777); pw=new PrintWriter(client.getOutputStream()); br=new BufferedReader(new InputStreamReader(System.in)); } pw.println(br.readLine()); pw.flush(); client.close(); } } public static void main(String[] args) { try { new MyClient(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 服務(wù)器端:MyServer import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class MyServer { private Socket socket; private ServerSocket ss; public MyServer() throws IOException{ ss=new ServerSocket(7777); while(true) { System.out.println("等待信息%%%%"); socket=ss.accept(); BufferedReader bReader=new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("your input is:"+bReader.readLine()); } } public static void main(String[] args) { try { new MyServer(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
|