\chapter{Asynchronous Communication}
Most communication human has is synchronous. One speaks, one listens. If they talk without order, that'll be a quarrel.

But in fact, most communication systems who are base on computers, they are asynchronous. Even if they seem to be synchronous, they are not. The communication transmission process takes time, so there's no 100 percent real-time existed in this world.

In this chapter, we'll talk about the asynchronous operation that we can use in Python, so we can use it later to build our communication system.


\section{asyncio}
\textbf{asyncio}\cite{asyncio} is a Python library for making an asynchronous program.


\subsection{A simple example}
\lstinputlisting[language=Python]{data/codes/4/1asyncio_example.py}

\noindent 
The output is:

\begin{lstlisting}
Hello ...
... World!
\end{lstlisting}

From the above result, we could see that even if we put the function2 before the function1, the program will still print the function1 string 'Hello' first, then print the function2 string 'World'.

It does so because of the function1 delays less time than function2, 1 less than 2. And they were started at the same time.

\section{A simple server and client program}
\subsection{server}
\lstinputlisting[language=Python]{data/codes/4/2asyncio_streams_server.py}

\subsection{client}
\lstinputlisting[language=Python]{data/codes/4/2asyncio_streams_client.py}

\subsection{summary}
The basic idea behind all of those codes is the same as we have seen before.

First, we have to create a server, which defines the IP address and port that we wanted the client to connect.

Then we create a client constantly access the IP address to get a connection, through that connection, we can send messages and receive messages from both sides.


\section{Keep the Connection or Not}
Most people thought that their communication connection is always on, but the truth is NO.

There's no such a network connection that keeps forever. Because we are using the Internet. The internet itself is packet-based, which means anything that was transferred based on the Internet should be split by pieces and delivered part by part.

That's how digit communication or modern communication works, they won't keep a connection always on, but they'll try to connect the server as often as possible.

Like, if the client connects the server per 1 second for information fetching. It will be enough for a human to get unimportant messages.

I say it is unimportant is because no one can take a big movement for 1 second. So the delay for the 1 second is not important for humans.