我已经能够从套接字接收文件并下载它,但当我尝试将消息从服务器推送到客户端时,消息永远不会显示在客户端。
以下是代码,任何帮助都将受到高度赞赏,因为我是网络编程的新手。
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
Buffer = 1024
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
f = open("FileFromServer.txt", "wb")
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(Buffer)
while data:
f.write(data)
print("from connected user: " + str(data))
data = conn.recv(Buffer)
f.close()
print 'Data Recivede'
datas = 'Recived the file Thanks'
if datas is not '':
conn.send(datas) # send data to the client
conn.close() # close the connection
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
with open('T.txt', 'rb') as f:
print 'file openedfor sending'
l = f.read(1024)
while True:
client_socket.send(l)
l = f.read(1024)
f.close()
print('Done sending')
print('receiving data...')
data = client_socket.recv(1024)
print data
client_socket.close() # close the connection
print 'conection closed
答案 0 :(得分:0)
问题是你的服务器和客户端套接字都在while循环中停留:
试试 client.py :
import socket
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
end = '$END MARKER$'
with open('T.txt', 'rb') as f:
print('file opened for sending')
while True:
l = f.read(1024)
if len(l + end) < 1024:
client_socket.send(l+end)
break
client_socket.send(l)
print('Done sending')
print('receiving data...')
data = client_socket.recv(1024)
print(data)
client_socket.close() # close the connection
print('conection closed')
<强> server.py 强>
import socket
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
Buffer = 1024
end = '$END MARKER$'
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
# receive data stream. it won't accept data packet greater than 1024 bytes
with open("FileFromServer.txt", "ab") as f:
while True:
data = conn.recv(Buffer)
if end in data:
f.write(data[:data.find(end)])
conn.send(b'Recived the file Thanks')
break
f.write(data)
conn.close()