In this article, an example of Python Socket to achieve a simple TCP Server/client function. Shared for your reference, as follows:
There are countless articles on the web about sockets. Record the bits and pieces of their own learning. For future review and study use.
socket Chinese translation is socket, always feel the words do not mean. Simple understanding is ip + port to form a management unit. It is also the program application call interface.
Here we start by describing howStart the tcp server。
The server part of the tcp connection, start an ip and port port, listen on the port port, when a request is received from the client, use a new port port2 to establish a connection with the client.
The process of socket start listening is:
Creating a socket
bind port (computing)
Start listening
Establish connection + continue listening
Code:
''' This is a testing program the program is used to start server ''' import socket import sys def start_tcp_server(ip, port): #create socket sock = (socket.AF_INET, socket.SOCK_STREAM) server_address = (ip, port) #bind port print 'starting listen on ip %s, port %s'%server_address (server_address) #starting listening, allow only one connection try: (1) except , e: print "fail to listen on port %s"%e (1) while True: print "waiting for connection" client,addr = () print 'having a connection' () if __name__ == '__main__': start_tcp_server('10.20.0.20', 12345)
There is a common trick here, in start_tcp_server, we most often use the local ip, for the generality of the program, it is best to use the call function to get the ip address.
Two functions are usedtogether with
('name')
ip = (())
But the problem is that normally the ip address you get is 127.0.0.1.
For ip obtained using configuration or dhcp, refer to the related articles on this site.
socket client initiates the connection
Process for:
Create Interface
initiate a connection
The interface creation parameters are the same as for the socket server
The function that initiates the connection is (ip,port)
The ip and port in this place are the ip and listening port of the socket server side.
Code Example:
# -*- coding: utf-8 -*- ''' This is a testing program the program is used to test socket client ''' import socket import sys def start_tcp_client(ip, port): #server port and ip server_ip = ip servr_port = port tcp_client = (socket.AF_INET, socket.SOCK_STREAM) try: tcp_client.connect((server_ip, server_port)) except : print 'fail to setup socket connection' tcp_client.close()
More about Python related content can be viewed on this site's topic: thePython Socket Programming Tips Summary》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques》
I hope that what I have said in this article will help you in Python programming.