This article example describes the implementation of Python using socket to simulate TCP communication. Shared for your reference. Specific implementation methods are as follows:
For the creation of the TCP server side, it is divided into the following steps:
Create a socket object (socket): two of the parameters are Address Family (e.g., AF_INET for IPV4, AF_INET6 for IPV6, and AF_UNIX for the UNIX domain protocol family), and socket type (e.g., SOCK_STREAM for TCP, SOCK_DGRAM for UDP).
Bind server address (bind): the parameter is a server address binary.
Listen: the parameter is the number of allowed connections.
Wait for a 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:
Python#! /usr/bin/python
# -*- coding: utf-8 -*-
import socket
sock = (socket.AF_INET, socket.SOCK_STREAM)
server_address = ('127.0.0.1', 12345)
print "Starting up on %s:%s" % server_address
(server_address)
(1)
while True:
print "Waiting for a connection"
connection, client_address = ()
try:
print "Connection from", client_address
data = (1024)
print "Receive '%s'" % data
finally:
()
where the first element of the server address binary is the server IP (left blank to listen at any IP) and the second element is the server port number.
And for TCP client, it usually includes the following steps:
Create socket object (socket): same as server side.
Connect to the server (connect): the parameter is the server address binary.
Send and receive data: same as server side.
Close connection: same as server side.
The sample code is as follows:
Python# /usr/bin/python
# -*- coding: utf-8 -*-
import socket
def check_tcp_status(ip, port):
sock = (socket.AF_INET, socket.SOCK_STREAM)
server_address = (ip, port)
print 'Connecting to %s:%s.' % server_address
(server_address)
message = "I'm TCP client"
print 'Sending "%s".' % message
(message)
print 'Closing socket.'
()
if __name__ == "__main__":
print check_tcp_status("127.0.0.1", 12345)
I hope that what I have described in this article will help you in your Python programming.