這將按照您的意圖工作,只是它會在每次發送新數據時都會覆蓋文件,而不會超時。 超時表示整個連接的結束。但是你可以很容易地重寫這個來將數據添加到相同的文件或創建一個新的文件或做任何你需要的。
#! /usr/bin/env python
from socket import AF_INET, SOCK_DGRAM
import socket
import threading
class Server (threading.Thread):
def __init__ (self, host="192.168.88.51", port=123, bufsize=128):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.bufsize = bufsize
self.done = threading.Event()
def opensock (self):
s = socket.socket(AF_INET, SOCK_DGRAM)
s.bind((self.host, self.port))
s.settimeout(0.001)
return s
def run (self):
host = self.host
port = self.port
self.s = s = self.opensock()
print "Waiting for connection on", host+":"+str(port)
while not self.done.isSet():
try:
data, addr = s.recvfrom(self.bufsize)
print "Connection from", addr
s.settimeout(1)
self.recvdata(data, s, addr)
s.settimeout(0.001)
except socket.timeout: pass
except:
raise
self.done.set()
s.close()
print "Server on '%s:%s' stopped!" % (host, port)
def recvdata (self, initdata, conn, addr):
bufsize = self.bufsize
filename = str(self.port)+".data"
print "Opening file", filename
f = open(filename, "wb")
print "Receiving & writingrest of data from", addr
data = initdata
while data and not self.done.isSet():
f.write(data)
try:
data, addr = conn.recvfrom(bufsize)
except socket.timeout: break
f.close()
if self.done.isSet():
print "Forcefully interrupted transmission"
else:
print "File Downloaded"
def stop (self):
self.done.set()
self.s.close()
servers = []
for port in xrange(123, 150):
try:
s = Server(port=port)
s.start()
servers.append(s)
except Exception as e:
print e
raw_input("Press enter to send data to one of ports for testing . . . ")
import random
a = servers[0].host
p = random.choice(servers).port
print "data will be sent to port '%s:%i'" % (a, p)
k = socket.socket(AF_INET, SOCK_DGRAM)
k.connect((a, p))
k.send("1234567890")
k.send("asdfghjkl")
k.send("0987654321")
k.close()
raw_input("Press enter to close the program . . . ")
# Stop all servers:
for s in servers:
s.stop()
# Make sure all of them terminated:
for s in servers:
s.join()
您需要創建一個對象來保存每個套接字連接。該對象將具有單獨的連接和偵聽方法。一旦你有了這個設置,你就可以在一個單獨的線程中運行每個對象的偵聽器方法。 – amicitas