Use Python socketserver to write time synchronization between server and client

Source: Internet
Author: User
Tags local time unpack


Because NTP often times out, so I wrote a simple time synchronization server, the client will synchronize the service side of the system time:


Service side:

#!/usr/local/python27/bin/python#coding:utf-8import timeimport loggingimport socketserverimport  structfrom daemonize import DaemonizeSERVER_HOST =  ' 0.0.0.0 ' server_port =  37123BUF_SIZE = 1024pid =  '/tmp/timeserver.pid ' Logger = logging.getlogger ( ' MyLogger ') logger.setlevel (logging. DEBUG) fh = logging. Filehandler (' TimeServer.log ') fh.setlevel (logging. DEBUG) formatter = logging. Formatter ('% (asctime) s - % (name) s - % (levelname) s - % (message) s ') Fh.setformatter (formatter) Logger.addhandler (FH) Keep_fds = [fh.stream.fileno ()]class threadedtcprequesthandler ( Socketserver.baserequesthandler):     def handle (self):         while true:            try:                  data = self.request.recv (buf_size)                  if not data:                     break                 logger.info ("Received: IP:% s message: %s " %  (self.client_address[0], data)                  i1, i2, message =  Struct.unpack ('!2b8s ',  data)                  if i1 == 3 and i2 == 7 and message = =  ' Get_time ':                     cur_time&nbsP;= int (Time.time ())                      response = struct.pack (' >2bi ',  i1, i2, cur_ Time)                      self.request.sendall (response)                      logger.info ("send: ip:%s message: % S " %  (self.client_address[0], cur_time))                  else:                     logger.error ("message error!")             except Exception, e:        &nbsP;        logger.error ("Error encountered:"  + str (e))                  break    def  finish (self):         self.request.close () class  Threadedtcpserver (socketserver.threadingmixin, socketserver.tcpserver):     passdef  main ():     server = threadedtcpserver ((Server_host, server_port),  threadedtcprequesthandler)     print  "server loop running ..."      server.serve_forever () #main () daemon = daemonize (app= "Timeserver",  pid=pid,  action=main, keep_fds=keep_fds) Daemon.start ()

Daemonize This is a third-party module, you can turn the script into a daemon, out of the terminal, detailed reference: https://pypi.python.org/pypi/daemonize/2.3.1

The struct module is to convert the data into binary, which is usually used in interaction with other programs, and I'm here to play.

Then there is nothing, just take the online demo rewrite the work function.


Client:

#!/usr/bin/python#coding:utf-8import subprocessimport socketimport timeimport sysimport  structSERVER_HOST =  ' 192.168.1.100 ' server_port = 37123buf_size = 1024def  client (Ip, port):     sock = socket.socket (Socket.AF_INET, socket . Sock_stream)     sock.connect ((ip, port))     message =  Struct.pack (' >2b8s ', 3, 7,  ' get_time ')     try:         sock.sendall (message)         response =  SOCK.RECV (buf_size)         i1, i2, cur_time =  struct.unpack ('!2bi ',  response)         formattime =  time.strftime ('%y-%m-%d %h:%m:%s ',  time.localtime (int (cur_time)))          ret&nbsP;= subprocess.call ('  date -s  '%s '   '  % formattime, shell=true)         print  "client received: %s format: %s " %  (response, formattime)     except Exception, e:         print  "encountered error:"  + str (e)          sys.exit (2)     else:        sock.close ()         return retif __name__ ==  "__main__":     client (Server_host, server_port)

The client is simpler, connect directly to the server with the socket, and then modify the local time after getting the message.

This article is from the "Operations Notes" blog, make sure to keep this source http://lihuipeng.blog.51cto.com/3064864/1619797

Use Python socketserver to write time synchronization between server and client

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.