In this paper, the implementation method of TCP communication using socket is described in the example of Python. Share to everyone for your reference. The implementation method is as follows:
For the creation of the TCP server side, it is divided into the following steps:
Create socket Object (socket): Where two parameters are address Family (for example, Af_inet is Ipv4,af_inet6 for UNIX domain protocol family), socket type (e.g. Sock_ Stream is tcp,sock_dgram to UDP).
Bind server address (BIND): The parameter is a server address of two tuples.
Listening (listen): The number of connections allowed for the parameter.
Wait for the request (accept).
Receive data (recv, Recvfrom, Recvfrom_into, Recv_into), send data (send, Sendall, sendto).
Close the connection (close).
The sample code is as follows:
The code is 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 ()
Where the server address is a two-tuple, the first element is the server IP (left blank for listening on any IP), and the second element is the server port number.
For the TCP client, the following steps are usually included:
Create socket Object (socket): Same server side.
Connection server (Connect): The parameter is a server address two tuple.
Send and receive data: Same server side.
Close connection: same server side.
The sample code is as follows:
The code is 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)
Hopefully this article will help you with Python programming.