Python network programming Create a SOCKETSERVERTCP server

Source: Internet
Author: User

#encoding =utf-8
#创建一个socketserverTCP服务器
#高级模块 to simplify the implementation of customers and servers
From Socketserver import (TCPServer as tcp,streamrequesthandler as SRH)
From time import CTime

Host = ' '
Port = 21567
Addr = (Host,port)

A subclass is derived from the Streamrequesthandler class of the #从 Socketserver
Class Myrequesthandler (ARH):
def Handel (self):
print ' Connected from ', self.client_address
Self.wfile.write (' [%s]%s '% (CTime (), Self.rfile.readline ()))
#用 the ReadLine () function to get the customer message, send the string to the client using the Write () function.

Tcpserv = TCP (Addr,myrequesthandler)
print ' Waiting for connection '
Tcpserv.serve_forever ()

#encoding =utf-8
# is a timestamp TCP client, and it knows how to Streamrequesthandler objects with Socketserver
Communication
From socket Import *

host = ' localhost '
Port = 21567
Bufsiz = 1024
Addr = (Host,port)

While True:
Tcpclientsock = socket (af_inet,sock_stream)
Tcpclientsock.connect (addr)
data = Raw_input (' > ')
If not data:
Break
Tcpclientsock.send ('%s\r\n '% data)
# We can use the ReadLine () function to get a customer message, using the Write () function to put the word
# string sent to the customer.
# in order to maintain consistency, we have to add a carriage return and a newline in the code on both sides of the client and server. In fact, you're in the code
# You can't see this, because we've reused the return and line feeds that our customers have come to pass.
data = TCPCLIENTSOCK.RECV (Bufsiz)
If not data:
Break
Print Data.strip ()

Tcpclientsock.close ()

Python network programming Create a SOCKETSERVERTCP server

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.