本文和大家分享的主要是python
中使用socket實(shí)現(xiàn)時(shí)間服務(wù)器相關(guān)內(nèi)容,一起來(lái)看看吧,希望對(duì)大家
學(xué)習(xí)python有所幫助。
創(chuàng)建一個(gè)TCP
的服務(wù)器,是很簡(jiǎn)單的,特別這是一個(gè)時(shí)間服務(wù)器。學(xué)習(xí)過(guò)網(wǎng)絡(luò)編程的人都知道,創(chuàng)建服務(wù)器就是先調(diào)用
bind
函數(shù)綁定,
接著調(diào)用listen
函數(shù)來(lái)監(jiān)聽(tīng),就可以完成服務(wù)器的創(chuàng)建。
下面來(lái)創(chuàng)建一個(gè)時(shí)間服務(wù)器,綁定端口為8037
:
# File: socket-example-2.py
import
socket
import struct,
time
# user-accessible port
PORT = 8037
# reference time
TIME1970 = 2208988800
# establish server
service =
socket.
socket(
socket.AF_INET,
socket.SOCK_STREAM)
service.bind(("", PORT))
service.listen(1)
print("listening on port", PORT)
while True: # serve forever
channel,
info = service.accept()
print("connection from",
info)
t = int(
time.
time()) + TIME1970
t = struct.pack("!I", t)
channel.send(t) # send timestamp
channel.
close() # disconnect
結(jié)果輸出如下:
listening on port 8037
connection from ('127.0.0.1', 52125)
在這個(gè)程序里,listen
監(jiān)聽(tīng)一個(gè)連接,后面使用無(wú)限循環(huán)調(diào)用
accept
函數(shù)來(lái)接收連接進(jìn)來(lái),然后創(chuàng)建
channel
的連接,
info
保存連接信息。后面把當(dāng)前系統(tǒng)發(fā)送回去。
用來(lái)測(cè)試這個(gè)服務(wù)器,可以使用下面的程序:
# File: socket-example-1.py
import
socket
import struct,
time
# server
HOST = '127.0.0.1'#"time.nist.gov"
PORT = 8037
# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800 # 1970-01-01 00:00:00
# connect to server
s =
socket.
socket(
socket.AF_INET,
socket.SOCK_STREAM)
s.connect((HOST, PORT))
# read 4 bytes, and convert to time value
t = s.recv(4)
t = struct.unpack("!I", t)[0]
t = int(t - TIME1970)
s.
close()
# print results
print("server time is",
time.ctime(t))
print("local clock is", int(
time.
time()) - t, "seconds off")
來(lái)源:
大坡3D
軟件開(kāi)發(fā)