实现一个时间服务器,客户端连接上服务端后,客户端发送的消息会加上时间戳后返回。
服务端
#coding:utf-8
from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
tcp_ser_socket = socket(AF_INET,SOCK_STREAM)
tcp_ser_socket.bind(ADDR)
tcp_ser_socket.listen(5)
while True:
print 'waiting for connection..'
tcp_client_socket , addr = tcp_ser_socket.accept()
print '...connected from:',addr
while True:
data = tcp_client_socket.recv(BUFSIZE)
if not data:
break
tcp_client_socket.send('[%s] %s' % (ctime(),data))
tcp_client_socket.close()
# 这句其实没用,实际中可以添加守护进程,
# 上面的while循环通过判断守护进程是否存在来决定是否要退出
tcp_ser_socket.close()
客户端
from socket import *
HOST = '192.168.233.130'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
tcp_client_socket = socket(AF_INET,SOCK_STREAM)
tcp_client_socket.connect(ADDR)
while True:
data = raw_input('> ')
if not data:
break
tcp_client_socket.send(data)
data = tcp_client_socket.recv(BUFSIZE)
if not data:
break
print data
tcp_client_socket.close()
运行服务端程序:
root@ubuntu:/home/fl# python tcp_server.py
waiting for connection..
运行客户端程序:
D:>C:\Python27\python client.py
> nihao
[Mon Aug 7 07:54:29 2017] nihao
> hello
[Mon Aug 7 07:54:39 2017] hello