簡體   English   中英

如何在 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM