Python TCP服务器在没有提示的情况下发送数据



我在python中开发应用程序时遇到问题。

我需要在没有提示的情况下将数据从服务器发送到客户端,但我在互联网上发现的所有例子都是echo服务器。

服务器应该具有静态IP(127.0.0.1(,并在第一次连接时保存客户端IP。例如,我需要每隔5秒(直到超时(将数据从服务器发送到客户端,而不需要服务器等待请求该数据。当然,客户端在自己的例程中发送另一个数据。

服务器脚本:

import socket
TCP_IP = "127.0.0.1"
TCP_PORT = 5010
BUFFER_SIZE = 512
MESSAGE = 'Hi'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
while(1):
s.listen()
conn, addr = s.accept()
print ('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: 
break
print ("received data: ", data.decode())
print ("address: ", addr[0])
conn.send(MESSAGE.encode())  # echo
print("Closing connection")
conn.close()

和客户端脚本:

import socket
import sys
import logging
import time
HOST, PORT = "127.0.0.1", 5010
data = " ".join(sys.argv[1:])
for x in range(100):
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect_ex((HOST, PORT))
sock.sendall(bytes(data + "n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
sock.close()
logging.info("Socket closed")
print("Sent:     {}".format(data))
print("Received: {}".format(received))
print("Size: ", sys.getsizeof(received), "bytes")
time.sleep(5)

我真的很感激你的帮助。

服务器保持连接并每5秒发送一次数据的示例。同时,服务器保持连接并在循环中接收数据。但它会阻塞服务器和客户端,循环应该在分离的线程中工作

服务器:

import socket
import time
import datetime

TCP_IP = "127.0.0.1"
TCP_PORT = 5010
BUFFER_SIZE = 512
MESSAGE = 'Hi'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen() # it can be before loop
while True:
conn, addr = s.accept()
print ('Connection address:', addr)
while True:
data = conn.recv(BUFFER_SIZE)
if not data: 
break
print ("received data: ", data.decode())
print ("address: ", addr[0])
conn.send(MESSAGE.encode())  # echo
# send data every 5 seconds - it should run in separated thread   
while True:
time.sleep(5)
conn.send(str(datetime.datetime.now()).encode())
print("Closing connection")
conn.close()

客户端

import socket
import sys
import logging
import time
HOST, PORT = "127.0.0.1", 5010
data = " ".join(sys.argv[1:])
for x in range(100):
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect_ex((HOST, PORT))
sock.sendall(bytes(data + "n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
print("Sent:     {}".format(data))
print("Received: {}".format(received))
print("Size: ", sys.getsizeof(received), "bytes")
# receive data periodically - it should run in thread
while True:
received = str(sock.recv(1024), "utf-8")
print("Received: {}".format(received))

sock.close()
logging.info("Socket closed")

编辑:带有threading的版本。用queue向线程发送消息并停止

服务器-经典结构。它可以同时与许多客户端一起工作

import socket
import time
import datetime
import threading
# --- functions ---
def process_client(conn, addr):
print('Connection address:', addr)
data = conn.recv(BUFFER_SIZE)
if not data: 
return
print("received data: ", data.decode())
print("address: ", addr[0])
conn.send(MESSAGE.encode())
# send data every 5 seconds
while True:
time.sleep(5)
conn.send( str(datetime.datetime.now()).encode() )
conn.close()
# --- main ---
TCP_IP = "127.0.0.1"
TCP_PORT = 5011
BUFFER_SIZE = 512
MESSAGE = 'Hi'
#all_threads = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen() # it can be before loop
while True:
print('wait for next client')
conn, addr = s.accept()
t = threading.Thread(target=process_client, args=(conn, addr))
t.start()
#all_threads.append(t)
#for t in all_threads: t.join()    
print("Closing connection")
s.close()

客户端-线程中的套接字,这样程序就可以做其他事情

import socket
import sys
import logging
import time
import threading
import datetime
import queue
# --- functions ---
def receive_data(q):
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect_ex((HOST, PORT))
sock.sendall(bytes(data + "n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
print("Sent:     {}".format(data))
print("Received: {}".format(received))
print("Size: ", sys.getsizeof(received), "bytes")
# receive data periodically - it should run in thread
while True:
received = str(sock.recv(1024), "utf-8")
print("Received: {}".format(received))
if not q.empty() and q.get() == 'stop':
break 
# sock.close() # doesn't need if you use `with ... as sock`
print("Socket closed")
# --- main ---
HOST, PORT = "127.0.0.1", 5011
data = " ".join(sys.argv[1:])
q = queue.Queue()
t = threading.Thread(target=receive_data, args=(q,))
t.start()
# other code
#while True:
for x in range(10):
print('    Local time:', datetime.datetime.now())
time.sleep(1)
q.put("stop") # message to thread to stop it
#t.join()

它需要一些try/except(即捕获Cltr+C并停止线程(和停止线程的代码。


BTW:我的其他答案中的一些例子furas/python examples/socket(在GitHub上(

相关内容

  • 没有找到相关文章

最新更新