java基礎筆記12 - 網路程式設計
阿新 • • 發佈:2022-03-09
十二 網路程式設計
1.概述
直接間接的使用挽留過協議,與其他計算機實現資料的交換
倆問題:
- 如何定位對方的主機,定位到特定的程序應用 IP+Port
- 如何可靠的進行資料傳輸 OSI參考模型和TCP/IP參考模型+各層的協議
2. IP Port
2.1 ip
java中使用InetAddress類表示一個地址
try { InetAddress inet1 = InetAddress.getByName("192.168.0.1"); System.out.println(inet1); //域名方式 InetAddress inet2 = InetAddress.getByName("www.baidu.com"); System.out.println(inet2.getHostName); //www.baidu.com sout(inet2.getHostAddress());//182.61.200.6 //本機地址 InetAddress localHost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); }
2.2 port:
0-1023:預先定義的公用埠:http 80
1024-49151:自定義埠號,如tomcat 8080,Mysql 3306,oracle 1521
49152-95535:動態/私有埠
Socket=ip+port
3.網路協議
3.1 傳輸層
3.1.1 UDP
不需要建立連線 (不可靠)
每個資料大小限制在64Kb
可以廣播
3.1.2 TCP
必須建立TCP連線,形成資料通道(三次握手)
TCP協議通訊的兩邊分別為客戶端和伺服器端
可以進行大資料量的傳輸
完畢需要釋放連線( 四次揮手)
通訊
@Test public void client(){ Socket socket= null; OutputStream os= null; try { InetAddress inet = InetAddress.getByName("localhost"); socket = new Socket(inet,8889); os = socket.getOutputStream(); os.write("我是客戶端mm".getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); }finally { //全部需要先判空,再try-catch os.close(); socket.close(); } } @Test public void server(){ ServerSocket ss = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos= null; try { ss = new ServerSocket(8889); socket = ss.accept(); is = socket.getInputStream(); //不建議這樣寫 // byte[] buffer=new byte[1024]; // int len; // while ((len=is.read(buffer))!=-1){ // String str=new String(buffer,0.len); // System.out.println(str); // } baos = new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int len; while ((len=is.read(buffer))!=-1){ baos.write(buffer,0,len); } System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); }finally { //全部需要先判空,再try-catch baos.close(); is.close(); socket.close(); ss.close(); } }