Just getting started with Python and implementing a helloworldProgram--- About the UDP socket communication demo.
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.