Python USES socket to simulate TCP communication
- 2020-04-02 14:20:55
- OfStack
In this paper, an example of Python using socket to simulate TCP communication. Share with you for your reference. The specific implementation method is as follows:
For the creation of TCP server, there are the following steps:
Create socket object (socket) : the two parameters are Address Family (such as AF_INET is IPV4, AF_INET6 is IPV6, AF_UNIX is UNIX domain protocol Family), socket type (such as SOCK_STREAM is TCP, SOCK_DGRAM is UDP).
Bind server address: the parameter is the server address binary group.
Listen: the parameter is the number of connections allowed.
Wait for a request (accept).
Receive data (recv, recvfrom, recvfrom_into, recv_into) and send data (send, sendall, sendto).
Close the connection.
The sample 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, in the server address binary, the first element is the server IP (left blank to listen in any IP), and the second element is the server port number.
For TCP client, the following steps are usually included:
Create socket object (socket) : same as the server side.
Connect server (connect) : the parameter is the server address binary group.
Send and receive data: same as server side.
Close connection: same as server end.
The sample 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)
I hope this article has helped you with your Python programming.