Python: tcp and udp network programming example of SocketServer

Source: Internet
Author: User

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 ()

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.