1. 程式人生 > >淺談TCP傳輸細節

淺談TCP傳輸細節

一、tcp是面向連線的網路傳輸,需要建立連線並經過三次握手

二:tcp客戶端的建立過程:

①建立socket物件,明確目的ip和埠號

socket s=new socket("192.168.1.100",10000);

②建立傳輸輸出通道

outputstream out=s.getoutputstream();

③輸出資訊

outputstream.write("你好".getBytes());

④接受服務端傳送來的資訊

inputstream in=s.getinputstream();

byte[] buf=new byte[1024];

int len=in.read(buf);

string text=new string(buf,0,len);

⑤關閉資源

s.close();

服務端的建立過程:

①建立服務端,並提供連線的埠號

serversocket ss=new serversocket(10000);

②連線客戶端

socket s=ss.accept();

③獲取ip 

string ip=s.getInetAddress().getHostAddress();

④建立傳輸通道

inputstream in =s.getInputStream();

⑤.讀取接受到的資訊,輸出到控制檯

byte[] buf=new byte[1024];

int len=inputStream.read(buf);

String text=new String(buf,0,len);

system.out.println(text+":"+ip);

⑥傳送資訊通知客戶端,已經收到資訊

outputstream out=s.getoutputstream();

out.write("收到".getbytes());

⑦關閉資源

s.close();

ss.close();