陳慶全
    • 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
    # Networking and Streams Julia provides a rich interface to deal with streaming I/O objects such as terminals, pipes and TCP sockets. This interface, though asynchronous at the system level, is presented in a synchronous manner to the programmer and it is usually unnecessary to think about the underlying asynchronous operation. This is achieved by making heavy use of Julia cooperative threading ([coroutine](@ref man-tasks)) functionality. ## Basic Stream I/O All Julia streams expose at least a [`read()`](@ref) and a [`write()`](@ref) method, taking the stream as their first argument, e.g.: ```julia julia> write(STDOUT,"Hello World"); # suppress return value 11 with ; Hello World julia> read(STDIN,Char) '\n': ASCII/Unicode U+000a (category Cc: Other, control) ``` Note that [`write()`](@ref) returns 11, the number of bytes (in `"Hello World"`) written to [`STDOUT`](@ref), but this return value is suppressed with the `;`. Here Enter was pressed again so that Julia would read the newline. Now, as you can see from this example, [`write()`](@ref) takes the data to write as its second argument, while [`read()`](@ref) takes the type of the data to be read as the second argument. For example, to read a simple byte array, we could do: ```julia julia> x = zeros(UInt8, 4) 4-element Array{UInt8,1}: 0x00 0x00 0x00 0x00 julia> read!(STDIN, x) abcd 4-element Array{UInt8,1}: 0x61 0x62 0x63 0x64 ``` However, since this is slightly cumbersome, there are several convenience methods provided. For example, we could have written the above as: ```julia julia> read(STDIN,4) abcd 4-element Array{UInt8,1}: 0x61 0x62 0x63 0x64 ``` or if we had wanted to read the entire line instead: ```julia julia> readline(STDIN) abcd "abcd" ``` Note that depending on your terminal settings, your TTY may be line buffered and might thus require an additional enter before the data is sent to Julia. To read every line from [`STDIN`](@ref) you can use [`eachline()`](@ref): ```julia for line in eachline(STDIN) print("Found $line") end ``` or [`read()`](@ref) if you wanted to read by character instead: ```julia while !eof(STDIN) x = read(STDIN, Char) println("Found: $x") end ``` ## Text I/O Note that the [`write()`](@ref) method mentioned above operates on binary streams. In particular, values do not get converted to any canonical text representation but are written out as is: ```jldoctest julia> write(STDOUT,0x61); # suppress return value 1 with ; a ``` Note that `a` is written to [`STDOUT`](@ref) by the [`write()`](@ref) function and that the returned value is `1` (since `0x61` is one byte). For text I/O, use the [`print()`](@ref) or [`show()`](@ref) methods, depending on your needs (see the standard library reference for a detailed discussion of the difference between the two): ```jldoctest julia> print(STDOUT, 0x61) 97 ``` ## IO Output Contextual Properties Sometimes IO output can benefit from the ability to pass contextual information into show methods. The [`IOContext`](@ref) object provides this framework for associating arbitrary metadata with an IO object. For example, [`showcompact`](@ref) adds a hinting parameter to the IO object that the invoked show method should print a shorter output (if applicable). ## Working with Files Like many other environments, Julia has an [`open()`](@ref) function, which takes a filename and returns an `IOStream` object that you can use to read and write things from the file. For example if we have a file, `hello.txt`, whose contents are `Hello, World!`: ```julia julia> f = open("hello.txt") IOStream(<file hello.txt>) julia> readlines(f) 1-element Array{String,1}: "Hello, World!" ``` If you want to write to a file, you can open it with the write (`"w"`) flag: ```julia julia> f = open("hello.txt","w") IOStream(<file hello.txt>) julia> write(f,"Hello again.") 12 ``` If you examine the contents of `hello.txt` at this point, you will notice that it is empty; nothing has actually been written to disk yet. This is because the `IOStream` must be closed before the write is actually flushed to disk: ```julia julia> close(f) ``` Examining `hello.txt` again will show its contents have been changed. Opening a file, doing something to its contents, and closing it again is a very common pattern. To make this easier, there exists another invocation of [`open()`](@ref) which takes a function as its first argument and filename as its second, opens the file, calls the function with the file as an argument, and then closes it again. For example, given a function: ```julia function read_and_capitalize(f::IOStream) return uppercase(readstring(f)) end ``` You can call: ```julia julia> open(read_and_capitalize, "hello.txt") "HELLO AGAIN." ``` to open `hello.txt`, call `read_and_capitalize on it`, close `hello.txt` and return the capitalized contents. To avoid even having to define a named function, you can use the `do` syntax, which creates an anonymous function on the fly: ```julia julia> open("hello.txt") do f uppercase(readstring(f)) end "HELLO AGAIN." ``` ## A simple TCP example Let's jump right in with a simple example involving TCP sockets. Let's first create a simple server: ```julia julia> @async begin server = listen(2000) while true sock = accept(server) println("Hello World\n") end end Task (runnable) @0x00007fd31dc11ae0 ``` To those familiar with the Unix socket API, the method names will feel familiar, though their usage is somewhat simpler than the raw Unix socket API. The first call to [`listen()`](@ref) will create a server waiting for incoming connections on the specified port (2000) in this case. The same function may also be used to create various other kinds of servers: ```julia julia> listen(2000) # Listens on localhost:2000 (IPv4) TCPServer(active) julia> listen(ip"127.0.0.1",2000) # Equivalent to the first TCPServer(active) julia> listen(ip"::1",2000) # Listens on localhost:2000 (IPv6) TCPServer(active) julia> listen(IPv4(0),2001) # Listens on port 2001 on all IPv4 interfaces TCPServer(active) julia> listen(IPv6(0),2001) # Listens on port 2001 on all IPv6 interfaces TCPServer(active) julia> listen("testsocket") # Listens on a UNIX domain socket/named pipe PipeServer(active) ``` Note that the return type of the last invocation is different. This is because this server does not listen on TCP, but rather on a named pipe (Windows) or UNIX domain socket. The difference is subtle and has to do with the [`accept()`](@ref) and [`connect()`](@ref) methods. The [`accept()`](@ref) method retrieves a connection to the client that is connecting on the server we just created, while the [`connect()`](@ref) function connects to a server using the specified method. The [`connect()`](@ref) function takes the same arguments as [`listen()`](@ref), so, assuming the environment (i.e. host, cwd, etc.) is the same you should be able to pass the same arguments to [`connect()`](@ref) as you did to listen to establish the connection. So let's try that out (after having created the server above): ```julia julia> connect(2000) TCPSocket(open, 0 bytes waiting) julia> Hello World ``` As expected we saw "Hello World" printed. So, let's actually analyze what happened behind the scenes. When we called [`connect()`](@ref), we connect to the server we had just created. Meanwhile, the accept function returns a server-side connection to the newly created socket and prints "Hello World" to indicate that the connection was successful. A great strength of Julia is that since the API is exposed synchronously even though the I/O is actually happening asynchronously, we didn't have to worry callbacks or even making sure that the server gets to run. When we called [`connect()`](@ref) the current task waited for the connection to be established and only continued executing after that was done. In this pause, the server task resumed execution (because a connection request was now available), accepted the connection, printed the message and waited for the next client. Reading and writing works in the same way. To see this, consider the following simple echo server: ```julia julia> @async begin server = listen(2001) while true sock = accept(server) @async while isopen(sock) write(sock,readline(sock)) end end end Task (runnable) @0x00007fd31dc12e60 julia> clientside = connect(2001) TCPSocket(RawFD(28) open, 0 bytes waiting) julia> @async while true write(STDOUT,readline(clientside)) end Task (runnable) @0x00007fd31dc11870 julia> println(clientside,"Hello World from the Echo Server") Hello World from the Echo Server ``` As with other streams, use [`close()`](@ref) to disconnect the socket: ```julia julia> close(clientside) ``` ## Resolving IP Addresses One of the [`connect()`](@ref) methods that does not follow the [`listen()`](@ref) methods is `connect(host::String,port)`, which will attempt to connect to the host given by the `host` parameter on the port given by the port parameter. It allows you to do things like: ```julia julia> connect("google.com",80) TCPSocket(RawFD(30) open, 0 bytes waiting) ``` At the base of this functionality is [`getaddrinfo()`](@ref), which will do the appropriate address resolution: ```julia julia> getaddrinfo("google.com") ip"74.125.226.225" ```

    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