Python3 Network Programming
Python provides network services at two levels of access:
- Low-level network services support the basic Socket, which provides the standard BSD Sockets API and gives access to all methods of the underlying operating system Socket interface.
- The high-level network service module SocketServer provides server-centric classes that simplify the development of network servers.
What is a Socket?
Socket, also called a socket endpoint, is how applications usually send requests to or respond to requests from the network, allowing communication between hosts or between processes on a single computer.
The socket() function
In Python, we use the socket() function to create a socket; the syntax is as follows:
socket.socket([family[, type[, proto]]])
Parameters
- family: the socket family can be AF_UNIX or AF_INET
- type: the socket type can be divided according to whether it is connection-oriented or connectionless
SOCK_STREAMorSOCK_DGRAM - proto: generally left blank, defaults to 0.
Socket object (built-in) methods
| function | Description |
|---|---|
| Server-side sockets | |
| s.bind() | Bind the address (host, port) to the socket; under AF_INET the address is represented as a tuple (host, port). |
| s.listen() | Start TCP listening. backlog specifies the maximum number of connections the operating system can queue before refusing connections. This value must be at least 1; for most applications 5 is sufficient. |
| s.accept() | Passively accept a TCP client connection, (blocking) waiting for a connection to arrive |
| Client-side sockets | |
| s.connect() | Actively initiate a TCP server connection. Generally the address format is a tuple (hostname, port); if the connection fails, a socket.error error is returned. |
| s.connect_ex() | An extended version of the connect() function that returns an error code instead of raising an exception when an error occurs |
| Socket functions for general use | |
| s.recv() | Receive TCP data, returned as a string; bufsize specifies the maximum amount of data to receive. flag provides additional information about the message and can usually be ignored. |
| s.send() | Send TCP data, sending the data in string to the connected socket. The return value is the number of bytes to be sent, which may be less than the byte size of string. |
| s.sendall() | Send TCP data completely. Send the data in string to the connected socket, but attempt to send all data before returning. Returns None on success, raises an exception on failure. |
| s.recvfrom() | Receive UDP data, similar to recv(), but the return value is (data, address). data is a string containing the received data and address is the socket address of the sender. |
| s.sendto() | Send UDP data to the socket; address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent. |
| s.close() | Close the socket |
| s.getpeername() | Return the remote address of the connected socket. The return value is usually a tuple (ipaddr, port). |
| s.getsockname() | Return the socket's own address. Usually a tuple (ipaddr, port) |
| s.setsockopt(level,optname,value) | Set the value of the given socket option. |
| s.getsockopt(level,optname[.buflen]) | Return the value of a socket option. |
| s.settimeout(timeout) | Set a timeout period for socket operations; timeout is a floating-point number in seconds. A value of None means there is no timeout period. Generally the timeout should be set right after creating the socket, since it may be used for connection operations (such as connect()) |
| s.gettimeout() | Return the current timeout value in seconds, or None if no timeout has been set. |
| s.fileno() | Return the socket's file descriptor. |
| s.setblocking(flag) | If flag is False, set the socket to non-blocking mode; otherwise set it to blocking mode (the default). In non-blocking mode, if recv() finds no data or send() cannot send data immediately, a socket.error exception is raised. |
| s.makefile() | Create a file object associated with this socket |
Simple Example
Server side
We use the socket module's socket function to create a socket object. The socket object can set up a socket service by calling other functions.
Now we can call the bind(hostname, port) function to specify the service's port。
Next, we call the socket object's accept method. This method waits for a client connection and returns a connection object representing the connection to the client.
The complete code is as follows:
Example
#!/usr/bin/python3
Filename: server.py
Import the socket and sys modules
import
socket
import
sys
Create a socket object
serversocket
=
socket
.
socket
(
socket
.
AF_INET
,
socket
.
SOCK_STREAM
)
Get the local host name
host
=
socket
.
gethostname
(
)
port
=
9999
Bind the port number
serversocket.
bind
(
(
host
,
port
)
)
Set the maximum number of connections; excess ones are queued
serversocket.
listen
(
5
)
while
True
:
Establish the client connection
clientsocket
,
addr
=
serversocket.
accept
(
)
(
"Connection address: %s"
%
str
(
addr
)
)
msg
=
'Welcome to Runoob Tutorial!'
"\r\n"
clientsocket.
send
(
msg.
encode
(
'utf-8'
)
)
clientsocket.
close
(
)
Client Side
Next we write a simple client example to connect to the service created above. The port number is 9999.
socket.connect(hostname, port ) method opens a TCP connection to the host hostname and the port port of the service provider. After connecting we can get data from the server; remember to close the connection when finished.
The complete code is as follows:
Example
#!/usr/bin/python3
Filename: client.py
Import the socket and sys modules
import
socket
import
sys
Create a socket object
s
=
socket
.
socket
(
socket
.
AF_INET
,
socket
.
SOCK_STREAM
)
Get the local host name
host
=
socket
.
gethostname
(
)
Set the port number
port
=
9999
Connect to the service, specifying the host and port
s.
connect
(
(
host
,
port
)
)
Receive less than 1024 bytes of data
msg
=
s.
recv
(
1024
)
s.
close
(
)
(
msg.
decode
(
'utf-8'
)
)
Now we open two terminals; in the first terminal run the server.py file:
$ python3 server.py
In the second terminal run the client.py file:
$ python3 client.py
欢迎访问Runoob Tutorial!
Now if we go back to the first terminal, we will see the following output:
连接地址: ('192.168.0.118', 33397)
Python Internet modules
The following lists some important modules for Python network programming:
| Protocol | Purpose | Port number | Python module |
|---|---|---|---|
| HTTP | Web page access | 80 | httplib, urllib, xmlrpclib |
| NNTP | Read and post news articles, commonly called "posts" | 119 | nntplib |
| FTP | File transfer | 20 | ftplib, urllib |
| SMTP | Send email | 25 | smtplib |
| POP3 | Receive email | 110 | poplib |
| IMAP4 | Retrieve email | 143 | imaplib |
| Telnet | Command line | 23 | telnetlib |
| Gopher | Information lookup | 70 | gopherlib, urllib |
For more content, see the official site's Python Socket Library and Modules。