Python network programming-TCP and UDP socket usage example, pythonudp
This article describes the use of TCP and UDP socket in Python network programming. We will share this with you for your reference. The details are as follows:
TCP protocol
Server:
#! /Usr/bin/env pythonfrom socket import * from time import ctimeHOST = ''PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpSerSock = socket (AF_INET, SOCK_STREAM) # create a server TCP socket tcpSerSock. bind (ADDR) tcpSerSock. listen (5) while True: print 'Waiting for connection... 'tcpclisock, addr = tcpSerSock. accept () # Wait for the client to connect to print '... connected from: ', addr while True: data = tcpCliSock. recv (BUFSIZ) # monitor whether the client sends messages if not data: break tcpCliSock. send ('[% s] % s' % (ctime (), data) tcpCliSock. close () tcpSerSock. close ()
Client:
#! /Usr/bin/env pythonfrom socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpCliSock = socket (AF_INET, SOCK_STREAM) # create a client TCP socket tcpCliSock. connect (ADDR) # connect to the server while True: data = raw_input ('>') if not data: break tcpCliSock. send (data) data = tcpCliSock. recv (BUFSIZ) # Listen to the client to send the message if not data: break print datatcpCliSock. close ()
UDP protocol
Server:
#! /Usr/bin/env pythonfrom socket import * from time import ctimeHOST = ''PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) udpSerSock = socket (AF_INET, SOCK_DGRAM) udpSerSock. bind (ADDR) while True: print 'Waiting for message... 'Data, addr = udpSerSock. recvfrom (BUFSIZ) # listen to and accept the message udpSerSock sent by the client. sendto ('[% s] % s' % (# Add a timestamp to the message and return it to the client ctime (), data), addr) print '... stored ed from and returned to: ', addrudpSerSock. close ()
Client:
#! /Usr/bin/env pythonfrom socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) udpCliSock = socket (AF_INET, SOCK_DGRAM) while True: data = raw_input ('>') if not data: break udpCliSock. sendto (data, ADDR) # send data to the server, ADDR = udpCliSock. recvfrom (BUFSIZ) # The client accepts timestamp data if not data: break print dataudpCliSock. close ()