#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