Python implements simple socket communication and pythonsocket Communication
This example describes how to implement simple socket communication in python. We will share this with you for your reference. The details are as follows:
I started to access python and implemented a helloworld Program-socket communication demo about udp.
First, the implementation on the server side is as follows:
Import socket, tracebackhost = ''# Bind to all interfaces port = 51500 # Step1: Create socket object s = socket. socket (socket. AF_INET, socket. SOCK_DGRAM) # Step 2: Set the socket option (optional) s. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1) # Step3: bind to a port s. bind (host, port) # Step4: Listen to the connection on this port while 1: try: message, address = s. recvfrom (8192) print "Got data from", address s. sendto ("Data is already ed succeefully. ", address) cipher T (KeyboardInterrupt, SystemExit): print" raise "raise cipher T: print" traceback "traceback. print_exc ()
If the host is left blank, it means it can be bound to all interfaces and addresses. No matter which client requests are sent, as long as they are bound to the same port, then the server can listen to this request.
In a tcp connection, the listen or accept function is required to listen to client requests, and a dedicated socket and remote connection are required.
Next, let's implement our client:
Import socket, sys # Step1: input host and port information host = raw_input ('Please input host name: ') textport = raw_input ('Please input textport:') # Step2: create socket object s = socket. socket (socket. AF_INET, socket. SOCK_DGRAM) try: port = int (textport) handle T ValueError: port = socket. getservbyname (textport, 'udp') # Step 3: Open the socket connection s. connect (host, port) # Step4: send data print "Enter data to transmit:" data = sys. stdin. readline (). strip () s. sendall (data) # Step 5: receive data from the server print "Looking for replies; press Ctrl-C or Ctrl-Break to stop" while 1: buf = s. recv (2048) if not len (buf): break sys. stdout. write (buf)
This example is as simple as the C language version. It seems that as long as you understand socket programming, it will be almost the same to implement it in different languages.