首页 > 其他 > 详细

网络编程01 - 客户端和服务端循环发送消息

时间:2019-05-27 00:57:51      阅读:189      评论:0      收藏:0      [点我收藏+]

需求:

  server端:接收时间戳时间,转换成格式化时间

  client端:每隔10秒中把时间戳发给server端,time.time()

1、时间格式转换模块time_convert.py

    模块说明:

  导入time模块,定义时间戳转成格式化时间(字符串时间)的函数custom_time(timestamp) ,因为time.localtime(secs) ,参数secs支持float类型,所以要判断函数custom_time(timestamp)中timestamp参数是否是float类型,如果不是需要转换timestamp参数类型为float类型,然后通过time.localtime(timestamp)把时间戳转换成结构化时间time_local,再通过time.strftime(‘%Y-%m-%d %H:%M:%S‘,time_local)把结构化时间time_local转换成格式化时间dt,并通过return 返回dt,到此时间格式转换完成。

import time

‘‘‘
时间戳转格式化时间(字符串时间)
‘‘‘

def custom_time(timestamp):
    if type(timestamp) == float:
        time_local = time.localtime(timestamp)
        dt = time.strftime(%Y-%m-%d %H:%M:%S,time_local)
    else:
        timestamp = float(timestamp)
        time_local = time.localtime(timestamp)
        dt = time.strftime(%Y-%m-%d %H:%M:%S, time_local)
    return dt

2、服务端代码:

import socket
import time_convert   #导入时间格式转换模块

server = socket.socket()
ip_port = (0.0.0.0,8001)
server.bind(ip_port)
server.listen()
conn,addr = server.accept()

while 1:
    from_client_msg = conn.recv(1024)
    client_time = from_client_msg.decode(utf-8)
    print(time_convert.custom_time(client_time))   #调用时间格式转换方法

conn.close()
server.close()

3、客户端代码:

import time
import socket

client = socket.socket()
ip_port = (127.0.0.1,8001)
client.connect(ip_port)

while 1:
    client_msg = str(time.time())     #获取当前时间戳,并转换数据类型为字符串
    str1 = client.send(bytes(client_msg.encode(utf-8)))   #编码发送数据
    print(client_msg)
    time.sleep(5)

 

网络编程01 - 客户端和服务端循环发送消息

原文:https://www.cnblogs.com/rubickcn/p/10928430.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!