Java Socket入門

來源:互聯網
上載者:User

標籤:hello   shu   system   三次   pack   body   取數   put   com   

Java Socket底層採用TCP/IP協議通訊,通訊細節被封裝,我們僅僅需要指定IP、連接埠,便能輕易地建立TCP或UDP串連,進行網路通訊。資料的讀寫,可以使用我們熟悉的stream進行操作。

TCP通訊中,服務端與用戶端是一對多的關係,如

Client發起串連請求後,Server端響應並建立一個Socket執行個體,與Client端一對一通訊。通訊完畢後,Client端與Server端的Socket執行個體各自關閉串連並銷毀,此次通訊結束。

發起串連的三向交握和關閉串連的四次揮手過程暫且不表,後續文章詳細介紹。下面看具體代碼

服務端代碼

package com.coshaho.learn.socket;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;/** * SocketServer.java Create on 2017年12月16日 下午11:42:03     * 類功能說明:   socket服務端 * @Author coshaho */public class SocketServer {    public static void main(String[] args) throws Exception     {        // 建立服務端        ServerSocket server = new ServerSocket(10000);                // 服務端阻塞式監聽用戶端串連請求        // 接收到串連請求,則建立一個socket執行個體,與用戶端通訊        Socket client = server.accept();                // 擷取InputStream讀取資料        InputStream in = client.getInputStream();        byte[] b = new byte[1024];        // 用戶端關閉輸出資料流後服務端會讀取到-1標誌        while(-1 != in.read(b))        {            System.out.println(new String(b));        }               // 擷取OutputStream輸出資料        OutputStream out = client.getOutputStream();        out.write("hello, client".getBytes());        // 輸出結束,關閉輸出資料流        client.shutdownOutput();               System.out.println("Server close. " + System.currentTimeMillis());        server.close();    }}

 

 用戶端代碼

package com.coshaho.learn.socket;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;/** * SocketClient.java Create on 2017年12月16日 下午11:42:53     * 類功能說明:   socket用戶端 * @Author coshaho */public class SocketClient {    public static void main(String[] args) throws Exception     {        // 請求串連服務端,握手成功,返回Socket執行個體        Socket client = new Socket("127.0.0.1",10000);                // 擷取輸入輸出資料流,讀寫資料(與服務端資料讀寫操作相同)        InputStream in = client.getInputStream();        OutputStream out = client.getOutputStream();                out.write("hello, server".getBytes());        client.shutdownOutput();                byte[] b = new byte[1024];        while(-1 != in.read(b))        {            System.out.println(new String(b));        }                System.out.println("Client close. " + System.currentTimeMillis());        client.close();    }}

 

Java Socket入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.