In this paper, we describe the implementation method of Python using socket to simulate TCP communication. Share to everyone for your reference. The implementation methods are as follows:
For TCP server-side creation, there are several steps:
Create a Socket object (socket): Two parameters are address Family (for example, Af_inet is ipv4,af_inet6 to Ipv6,af_unix to UNIX domain protocol family), socket type (such as Sock_ Stream is tcp,sock_dgram as UDP).
Bind server address (BIND): The parameter is a server address two tuple.
Listener (Listen): parameter is the number of connections allowed.
Wait for request (accept).
Receive data (recv, Recvfrom, Recvfrom_into, Recv_into), send data (send, Sendall, sendto).
Closes the connection (close).
The sample code is as follows:
Copy Code code as follows:
Python SOCKET:TCP Server
python#! /usr/bin/python
#-*-Coding:utf-8-*-
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
server_address = (' 127.0.0.1 ', 12345)
Print "Starting up on%s:%s"% server_address
Sock.bind (server_address)
Sock.listen (1)
While True:
Print "Waiting for a Connection"
Connection, client_address = Sock.accept ()
Try
Print "Connection from", client_address
data = CONNECTION.RECV (1024)
print ' Receive '%s '% data
Finally
Connection.close ()
In the server address two tuple, the first element is the server IP (left blank for any IP listening), and the second element is the server port number.
For TCP client, the following steps are usually included:
Create a Socket object (socket): On the same server side.
Connection server (Connect): The parameter is a server address two tuple.
Send and receive data: On the same server side.
Close connection: same server side.
The sample code is as follows:
Copy Code code as follows:
Python SOCKET:TCP Client
python#/usr/bin/python
#-*-Coding:utf-8-*-
Import socket
def check_tcp_status (IP, port):
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
server_address = (IP, port)
print ' Connecting to%s:%s. '% server_address
Sock.connect (server_address)
message = "I ' m TCP client"
print ' sending '%s '% message
Sock.sendall (Message)
print ' Closing socket. '
Sock.close ()
if __name__ = = "__main__":
Print Check_tcp_status ("127.0.0.1", 12345)
I hope this article will help you with your Python programming.