59
1.
Server
Here we provide a pseudocode which creates a universal TCP server for explanation. Note
that this is just one of the methods for server design. After you have a good knowledge about
it, you can alter the pseudocode as you want:
s
=
socket
(
)
# Create a socket for the server.
s
.
bind
(
)
# Bind the address to the socket.
s
.
listen
(
)
# Listen to the connection.
inf_loop
:
# Indefinite loop of the server.
c
=
s
.
accept
(
)
# Accept the connection from the client.
comm_loop
:
# Communication loop.
c
.
recv
(
)/
c
.
send
(
)
# Dialog (receiving or sending data)
c
.
close
(
)
# Close the socket of the client.
s
.
close
(
)
# Close the socket of the server (optional).
All kinds of socket can be created via the function
socket.socket( )
and then bound with IP
address and port by the function
bind( )
. Since TCP is a connection-oriented communication
system, some settings need to be completed before the TCP server starts operation. The TCP
server must "listen" to connections from the client.
After the settings are done, the server will enter an indefinite loop. A simple, like single-thread,
server will call the function
accept( )
to wait for the coming connection. By default, the
function
accept( )
is a blocking one, which means it is suspended before the connection
comes. Once a connection is received, the function
accept( )
returns a separate client
socket for the subsequent communication. After the temporary socket is created,
communication begins. Both the server and client use the new socket for data sending and
receiving. The communication does not end until either end closes the connection or sends
a null character string.
SunFounder