Python: tcp and udp network programming example of SocketServer
Example of a tcp network program written using the SocketServer module (socketserver in python3:
#! /Usr/bin/env python
# Server
From SocketServer import TCPServer as TCP, StreamRequestHandler as SRH
Class MyRequestHandler (SRH ):
Def handle (self ):
Print I am server and recved: % s from % s % (self. rfile. readline (). strip (), self. client_address)
Self. wfile. write (I am server)
TcpServ = TCP (HOST, PORT), MyRequestHandler)
TcpServ. serve_forever ()
######################################## ########
#! /Usr/bin/env python
# Client
From socket import *
While True:
TcpCliSock = socket (AF_INET, SOCK_STREAM)
TcpCliSock. connect (HOST, PORT ))
TcpCliSock. send (I am client)
Data = tcpCliSock. recv (BUFSIZE)
If not data:
Break
Print I am client and recved:, data
TcpCliSock. close ()
######################################## #########################
Example of a udp network program programmed using the SocketServer module:
#! /Usr/bin/env python
# Server
From SocketServer import into ramrequesthandler as DRH, UDPServer as UDP
Class MyRequestHandler (DRH ):
Def handle (self ):
Print I am server and recved: % s from % s % (self. rfile. readline (), self. client_address)
Self. wfile. write (I am server)
Ss = UDP ('localhost', 6543), MyRequestHandler)
Ss. serve_forever ()
######################################## ######################
#! /Usr/bin/env python
# Client
Www.bkjia.com
From socket import *
While True:
Cs = socket (AF_INET, SOCK_DGRAM)
Cs. sendto (I am client, (HOST, PORT ))
Data, saddr = cs. recvfrom (BUFSIZE)
If not data:
Break
Print 'I am client and recved: % s from % s' % (data, saddr)
Cs. close ()