1.服務器端java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class HelloWorldServer { public static void main(String[] args) { ServerSocket server = null; BufferedReader reader = null; Socket client = null; try { server = new ServerSocket(9000);//建立ServerSocket對象,並綁定端口 client = server.accept();//調用accept方法,等待客戶端的鏈接 InputStream in = client.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); String str = reader.readLine(); System.out.println(str); } catch (IOException e) { e.printStackTrace(); }finally{ try{ if(client!=null){ client.close(); } }catch(IOException e){ e.printStackTrace(); } } } }
2.客戶端編程
import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class HelloWorldClient { public static void main(String[] args) { Socket client = null; PrintWriter writer = null; try { client = new Socket("www.feifeishi.cn", 9000);//www.feifeishi.cn是個人云服務器 OutputStream out = client.getOutputStream(); writer = new PrintWriter(out); Scanner sc=new Scanner(System.in); String aa=sc.nextLine(); writer.print(aa); writer.flush(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try{ if(writer!=null){ writer.close(); } if(client!=null){ client.close(); } }catch(IOException e){ e.printStackTrace(); } } } }
3.運行服務器
將服務器端放到服務器上並運行spa
運行服務器端.net
正在等待客戶端接入,而後本地運行客戶端code
控制檯輸入你好,而後服務器端接收並顯示你好server
4.拓展對象