Ashley
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Socket tags: hpcai --- # Socket Programming [TOC] ## Linux Kernel is implement in three layers 1. the socket interface 2. Protocol drivers 3. Network device drivers * 在真正談socket programming之前,我們要先初步的了解socket * 第一部分the socket interface負責的工作就是在**接受訊息**並且**傳遞訊息**到正確的protocol drivers * 第二部分Protocol drivers主要做的事就是**處理封包**並決定此封包要送到哪個device * 第三部分Network device drivers是去真的**聯絡**要處理這件事情的**硬體** ## 寫Socket常用的指令 * socket()/ bind()/ accept()/ listen() * 第一個socket()目的就是創建一個socket * 後面的bind()/accept()/listen()主要是用來設定這個socket * select()/ poll()/ epoll() * waiting for event 我的理解是:如果要對event做事情的時候我們就需要拿著這個event * send()/ recv() * TCP * 如果你的socket要用TCP就要用這兩個 * sendto()/ recvform() * UDP * 如果你的socket要用UDP就要用這兩個 * close()/ shutdown() * 當資料指令傳遞完成後就要把剛開始建立的socket關掉 ## TCP socket (connection) ![](https://i.imgur.com/pjSU1rE.png) * 左邊是Server方,右邊是Client(我們比較像是這一方) * Server方,首先先建立一個socket然後用bind()/listen()去設定這個創建的socket * 當我們Client要傳送一個指令給Server方時,我們也要先創建一個socket,然後因為我們是要**使用TCP的方式,因此我們必須將Server跟client的socket透過connect()和accept()連接起來** * ==TCP和UDP最大的不同就在於是否有建立這個connection== * 建立這個connection的功用就在於當我們傳遞資料有錯誤時,這個地方回傳一些值,讓我們知道我們的資料傳遞有錯誤,並且重傳,也就是一個除錯的機制,所以我們才會說**TCP是一個有可靠性的傳遞方式** * 再來的send()跟recv()就是發送/傳送指令的function ## UDP socket (connectionless) ![](https://i.imgur.com/EU6jSaf.png) * 跟上面的TCP socket比較就可以發現它少了connection,所以明顯這樣的傳遞是比較**快**的,但也因為這樣少了除錯的機制,所以它是一個**沒有可靠性**的傳遞方式 ## Server's Address * 為什麼需要找server address * 因為我們寫TCP socket時需要將Client的socket **connect to server** * 常見的表示方式(常見的name) * **"www.cnn.com"**, with a service which is **"http"** * Socket address * socket address is basically in the format of an **IP address** and **a port number** * **"64.236.16.20"** and **"80"** * Get address funtion ```c= int getaddrinfo(char *node, //例如:"www.cnn.com" 或 IP char *service, //例如:"http" 或 port number struct addrinfo *hints, struct addrinfo **result) ``` ```c= struct addrinfo{ int ai_flags; int ai_family; //例如: AF_INET for IPv4 int ai_socketype; //例如: SOCK_STREAM for TCP int ai_protocol; //例如: IPPROTO_TCP size_t ai_addrlen; char *ai_canonname; struct sockaddr *ai_addr; //指向sockaddr struct struct addrinfo *ai_next; } ``` ```c= /*Example*/ hints.ai_family = AF_UNSPEC; //不管IPv4或IPv6 hints.ai_socktype = SOCK_STREAM; //for TCP int status = getaddrinfo("www.cnn.com", "80", &hints, &result); ``` * 解釋上述function -- *node: host name or IP address -- *service: service listed or port number -- *hints: 看我們要轉成什麼樣子都是在這個參數調整 -- **result: 指向結果 ## Client ### Client: Creating a Socket > <font color="#2231ff">**int socket (int domain, int type, int protocol)**</font> * Return * Return a file descriptor :::spoiler #### file descriptor(補充) * 中文翻譯:檔案描述符 * 形式上是一個非負整數,實際上是一個索引值(指向一個檔案的一種抽象概念) * 缺點: * 在非UNIX/Linux作業系統上無法基於這一概念進行編程(在windows下的檔案描述符記作HANDLE) * 因為檔案描述符在形式上不過是個整數,因此當代碼量增大時,容易和資料搞混 ::: * Arguments * domain: family * PE_INET for IPv4 * PE_INET6 for IPv6 * type: 要如何communication * SOCK_STREAM for TCP * SOCK_DGRAM for UDP * protocol: 特定的協約 * 不特定我們用"UNSPEC" * PF_INET跟SOCK_STREAM已經指向TCP,因此我們在這裡特別放什麼(原話:PF_INET and SOCK_STREAM already implies that it is going to use TCP so we do not need to put that under the protocol.) ```c= /*example*/ //跟上面的example有關 sockfd = socket(result->ai_family, result->ai_socktype, result->ai_protocol); ``` ### Client: Connecting Socket to the Server ![](https://i.imgur.com/sQWVbXE.jpg) * Return * Return 0 表示成功 * Return -1 表示錯誤 * Arguments * sockfd: Client建立socket時回傳的file descriptor * *server_address: server的address * addrlen: server的address的長度 ```c= /*example*/ //跟上面的example有關 connect(sockfd, result->ai_addr, result->ai_addrlen); ``` ### Client: Sending Data ![](https://i.imgur.com/TaWERed.jpg) * Return * Return number of bytes written (成功傳送時,返回值是傳送的資料長度) * Return 0表示結束 * Return -1表示錯誤 * Arguments * sockfd: Client建立socket時回傳的file descriptor * *msg: 指向要傳送資料的buffer * len: length of buffer * flags: ==下次會說==,這次沒有多解釋 #### 說明 * send() is <font color="#f00">blocking</font> * 所謂blocking就是指他是會做到完成,像是如果我們要傳1MB的資料,然後我們叫send(),那麼他就會一直傳,傳到1MB到達目的地時,才停止動作。 ### Client: Receiving Data ![](https://i.imgur.com/huqxLVv.jpg) * Return * Return number of characters read (成功接收時,返回值是接收到的資料長度) * Return 0表示結束 * Return -1表示錯誤 * Arguments * sockfd: Client建立socket時回傳的file descriptor * *buf: 指向要存放資料的buffer * len: size of buffer * flags同上 #### 說明 * Why we need len? <font color="#888888">為了確保我們給的buffer夠大</font> * recv() is <font color="#f00">blocking</font> ## Sever ### Sever: Creating a Socket > <font color="#2231ff">**int socket (int domain, int type, int protocol)**</font> 跟client建立socket時一樣 :::spoiler * Return * Return a file descriptor * Arguments * domain: family * PE_INET for IPv4 * PE_INET6 for IPv6 * type: 要如何communication * SOCK_STREAM for TCP * SOCK_DGRAM for UDP * protocol: 特定的協約 * 不特定我們用"UNSPEC" * PF_INET跟SOCK_STREAM已經指向TCP,因此我們在這裡特別放什麼(原話:PF_INET and SOCK_STREAM already implies that it is going to use TCP so we do not need to put that under the protocol.) ::: ### Server: Bind Socket Bind socket to the **local address and port number** ![](https://i.imgur.com/93KFx6M.png) * Return * Return 0表示成功 * Argements * sockfd: Server建立socket時回傳的file descriptor * *my_addr: 主機的IP address 和 port number * addrlen: address's length ### Server: Allowing Client to Wait 將Server的socket設定為**可以接受建立連線** > <font color="#2231ff">**int listen (int sockfd, int backlog)**</font> * Return * Return 0 表示成功 * Return -1 表示錯誤 * Arguments * sockfd: Server建立socket時回傳的file descriptor * backlog: 還未完成連線請求的最大數量(acceptable backlog) #### 說明 * listen()並未開始接收連線,只是設置socket為listen模式,真正接收client端連線的是accept()。 * listen() is <font color="#F00">non-blocking</font> :::spoiler ### blocking v.s non-blocking 用read()來說,如果我們使用**blocking read**,那麼讀取資料時就會因為另一端尚未寫入資料而**停止動作** 相反的,如果我們使用**non-blocking read**,那麼我們呼叫read()讀取時就會**立即返回**,但實際上我們不一定有讀到資料 ::: ### Sever: Accepting Client Connection ![](https://i.imgur.com/cVBPSNE.png) * Return * a file descriptor of socket for this new connection(回傳一個新的file descriptor) * Arguments * sockfd: Server建立socket時回傳的file descriptor * *addr: 要連接的Client的address and port * *addrlen: Client address's length #### 說明 * accept() is <font color="#f00">blocking</font> ## Client and Server: Cleaning House > <font color="#2231ff">**int close (int sockfd)**</font> * Return 0 表示成功 * Argument - sockfd: 要關掉的socket的file descriptor ## Reference 關鍵字可搜索:socket + 想要知道的function名稱 - [socket + send()/recv()](https://www.itread01.com/content/1549576655.html) (這個每個function都有講到但是翻譯比較大陸) - [socket + listen()](http://stenlyho.blogspot.com/2008/08/socket-listen.html) - [當send被block的時候](http://neokentblog.blogspot.com/2016/10/send-block.html) - [更詳細的socket.send](https://docs.microsoft.com/zh-tw/dotnet/api/system.net.sockets.socket.send?view=net-5.0) - [getaddrinfo()](https://beej-zhtw-gitbook.netdpi.net/system_call_huo_bust/getaddrinfoff0d_zhun_bei_kai_shi_ff01)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully