天天看點

用戶端服務端互動

*

  * 示範TCP傳輸

  * 1.分用戶端對應對象Socket、服務端對應ServerSocket

  */

 //需求:給服務端資訊,并且服務端回複資料

 /*步驟:

  * 1.建立Socket服務,并指定要連接配接的主機和端口

  * 2.擷取socket中的輸出流,并将資料寫到該流中,通過網絡發送給服務端

  * 3.擷取socket流中的輸入流,将服務端回報的資料擷取到,并列印

  * 4.關閉用戶端資源

  * 

  */

 public class TcClient {

 public static void main(String[] args) throws UnknownHostException, IOException {

//建立用戶端的socket服務,指定目的主機和端口

Socket s=new Socket("ip",10004);

OutputStream out=s.getOutputStream();//輸出流

out.write("tcp come".getBytes());


InputStream in=s.getInputStream();

byte[] buf=new byte[1024];

 int len=in.read(buf);

 System.out.println(new String(buf,0,len));

s.close();

 }

 }