如何在 Python 中从服务器向客户端发送连续数据?

How to send continous data from server to client in Python?

我正在构建一个服务器来向 Python 中的客户端发送数据。我想不断发送时间,直到客户端关闭连接。到目前为止,我已经完成了:

对于服务器:

import socket
from datetime import datetime

# take the server name and port name
host = 'local host'
port = 5001

# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
                  socket.SOCK_STREAM)

# bind the socket with server
# and port number
s.bind(('', port))

# allow maximum 1 connection to
# the socket
s.listen(1)

# wait till a client accept
# connection
c, addr = s.accept()

# display client address
print("CONNECTION FROM:", str(addr))

dateTimeObj = str(datetime.now())
print(dateTimeObj)

c.send(dateTimeObj.encode())

# disconnect the server
c.close()

对于客户:

import socket

# take the server name and port name

host = 'local host'
port = 5001

# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
                  socket.SOCK_STREAM)

# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))

# receive message string from
# server, at a time 1024 B
msg = s.recv(1024)

# repeat as long as message
# string are not empty
while msg:
    print('Received date :' + msg.decode())
    msg = s.recv(1024)

# disconnect the client
s.close()

如何修改服务器以连续发送当前日期?目前,服务器只是发送一个日期并关闭连接。

你需要使用 While True 循环。

import socket
from datetime import datetime

# take the server name and port name
host = 'local host'
port = 5001

# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
                  socket.SOCK_STREAM)

# bind the socket with server
# and port number
s.bind(('', port))

# allow maximum 1 connection to
# the socket
s.listen(1)

# wait till a client accept
# connection
while True:
    c, addr = s.accept()

    # display client address
    print("CONNECTION FROM:", str(addr))

    dateTimeObj = str(datetime.now())
    print(dateTimeObj)

    c.send(dateTimeObj.encode())

    # disconnect the server
    c.close()

客户:

import socket

# take the server name and port name

host = 'local host'
port = 5001

# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
                  socket.SOCK_STREAM)

# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))

# receive message string from
# server, at a time 1024 B
while True:
    msg = s.recv(1024)

    # repeat as long as message
    # string are not empty
    while msg:
        print('Received date :' + msg.decode())
        msg = s.recv(1024)

# disconnect the client
s.close()