The best Python Network Programming Tutorial In 2024, In this tutorial you can learn What is Socket?,socket () function,Simple example,Python Internet modules,
Python offers two levels of access network services. :
Socket also known as "socket", the application is usually issued by a "socket" to the network request or response network request, so that the process between hosts or between a computer on can communicate.
Python, we use the socket () function to create a socket, syntax is as follows:
socket.socket([family[, type[, proto]]])
SOCK_STREAM
or SOCK_DGRAM
function | description |
---|---|
Server socket | |
s.bind () | Bind address (host, port) to the socket at AF_INET, in the form of a tuple (host, port) indicates the address. |
s.listen () | Start TCP listening. backlog specified before rejecting the connection, the operating system can suspend the maximum number of connections. This value is at least 1, most applications can be set to 5. |
s.accept () | Passive acceptance of TCP client connections (blocking) waiting for the arrival of |
Client socket | |
s.connect () | Active initialize TCP server connections. General address of the format of tuples (hostname, port), if the connection error, an error is returned socket.error. |
s.connect_ex () | connect () extended version of the function returns an error code when an error instead of throwing an exception |
Socket functions public purposes | |
s.recv () | Receive TCP data, the data is returned as a string, specify the maximum amount of data to be received bufsize. Provide additional information about the message flag can usually be ignored. |
s.send () | Send TCP data, sends the data string to the socket connection. The return value is the number of bytes to send, this number may be less than the string of bytes. |
s.sendall () | Complete sending TCP data, complete transmit TCP data. It sends the data string to the socket connection, but before returning will try to send all the data. Successful return None, failure exception is thrown. |
s.recvform () | Receiving UDP data () is similar to recv, but the return value is (data, address). Wherein the data is a string containing the received data, address data is sent socket address. |
s.sendto () | Send UDP data, send data to a socket, address is in the form of (ipaddr, port) tuple specified remote address. The return value is the number of bytes sent. |
s.close () | Close the socket |
s.getpeername () | Returns the connection socket remote address. The return value is usually a tuple (ipaddr, port). |
s.getsockname () | Returns the socket's own address. Usually a tuple (ipaddr, port) |
s.setsockopt (level, optname, value) | Set the value of a given socket option. |
s.getsockopt (level, optname [.buflen]) | The return value of the socket option. |
s.settimeout (timeout) | Set socket operation timeout period, timeout is a floating-point number, in seconds. None value indicates no time-out period. Generally, time-out period should just create a socket set, because they may be used to operate the connection (such as connect ()) |
s.gettimeout () | Returns the value of the current time-out period, in seconds, if there is no set time-out period, returns None. |
s.fileno () | Returns a socket file descriptor. |
s.setblocking (flag) | If the flag is 0, the socket is set to non-blocking mode, otherwise the socket to blocking mode (the default value). Non-blocking mode, if you call recv () did not find any data, or send () call can not immediately send data, it would cause socket.error exception. |
s.makefile () | Create a relevant documents in connection with the socket |
We use the socket modulesocket function to create a socket object.socket object can call other functions to set up a socket service.
Now we can specify the services by callingbind (hostname, port) functionport (port).
Next, we call the acceptmethod of socket objects. The method waits for the client connection and returnconnectionobject that represents connected to the client.
The complete code is as follows:
#!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名:server.py import socket # 导入 socket 模块 s = socket.socket() # 创建 socket 对象 host = socket.gethostname() # 获取本地主机名 port = 12345 # 设置端口 s.bind((host, port)) # 绑定端口 s.listen(5) # 等待客户端连接 while True: c, addr = s.accept() # 建立客户端连接。 print '连接地址:', addr c.send('欢迎访问本教程!') c.close() # 关闭连接
Next we write a simple client to connect to the service instances created above. Port number is 12345.
socket.connect (hosname, port) method opens a TCP connection to the host for thehostnameport toportservice providers.Once connected we can post-data from the server, remember, after the completion of the operation need to close the connection.
The complete code is as follows:
#!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名:client.py import socket # 导入 socket 模块 s = socket.socket() # 创建 socket 对象 host = socket.gethostname() # 获取本地主机名 port = 12345 # 设置端口好 s.connect((host, port)) print s.recv(1024) s.close()
Now we even have to open the terminal, the first terminal performs server.py file:
$ python server.py
The second terminal performs client.py file:
$ python client.py 欢迎访问本教程!
This is our first and then open a terminal, you will see the following information is output:
连接地址: ('192.168.0.118', 62461)
Here are some important module Python network programming:
protocol | Useful function | The port number | Python Modules |
---|---|---|---|
HTTP | Web access | 80 | httplib, urllib, xmlrpclib |
NNTP | Reading and posting news articles, known as the "post" | 119 | nntplib |
FTP | file transfer | 20 | ftplib, urllib |
SMTP | send email | 25 | smtplib |
POP3 | incoming mail | 110 | poplib |
IMAP4 | Get Mail | 143 | imaplib |
Telnet | Command Line | twenty three | telnetlib |
Gopher | Find information | 70 | gopherlib, urllib |
More details can be found in the official website of the Python the Socket Library and the Modules .