简体   繁体   English

Python套接字文件服务器

[英]Python socket file server

There are many questions on stackoverflow discussing the client server model for sending and receiving files with python. 在stackoverflow上有很多问题,讨论了使用python发送和接收文件的客户端服务器模型。

My question is a little different in that I want to create a python 'server socket', which listens on some port and then pushes a file to whoeever connects to that port. 我的问题有点不同,我想创建一个python“服务器套接字”,它侦听某个端口,然后将文件推送给连接到该端口的任何人。

I'm using the code below, however when I connect to the socket I do not receive the file. 我正在使用下面的代码,但是当我连接到套接字时,我没有收到文件。

s = socket.socket()        
s.bind((socket.gethostname(), 2048))
f = open('/tmp/test','rb')
s.listen(5)           
while True:
    c, addr = s.accept()
    print 'Connection from ', addr
    l = f.read(1024)
    while (l):
       print "Sending"
       s.send(l)
       l = f.read(1024)
    f.close()
    s.shutdown(socket.SHUT_WR)
    c.close()

Can anyone explain why this doesn't work? 谁能解释为什么这行不通?

You have four problems here. 您在这里有四个问题。

s.bind((socket.gethostname(), 2048))

gethostname() returns the name of your machine, not an address you can bind to. gethostname()返回您计算机的名称,而不是您可以绑定到的地址。 If you want to bind to all interfaces, just like s.bind(('', 2048)) . 如果要绑定到所有接口,就像s.bind(('', 2048))

s.send(l)

You're trying to send on the listener socket, not the connected client socket. 您正在尝试发送侦听器套接字,而不是连接的客户端套接字。 Use c.send(l) . 使用c.send(l) You make the same mistake later by calling s.shutdown instead of c.shutdown ; 您稍后通过调用s.shutdown而不是c.shutdown犯了同样的错误; you need it to fix it there, too. 您也需要用它来修复它。

s.send(l)

You're using send instead of sendall , and not checking the return value. 您使用的是send而不是sendall ,而不检查返回值。 You'll usually get away with this when your buffers are this small, but why accept "usually"? 当您的缓冲区很小时,通常可以避免这种情况,但是为什么要“通常”接受呢?

f.close()

Since you only open the file once, before accepting the first connection, and then you close it for each connection, the second client is just going to cause an exception as you try to read from a closed file. 因为你只open文件一次,接受第一个连接之前,然后close它为每个连接,第二客户端仅仅是将引发异常,当你试图从一个封闭的文件中读取。 Either move the open into the loop, or replace the f.close() with f.seek(0) . open环移动到循环中,或将f.close()替换为f.seek(0)

You are trying to send on the server socket s , while you need to do that on the newly accepted client socket c . 您正在尝试在服务器套接字s上发送,而您需要在新接受的客户端套接字c

Listening socket ( s here) can only accept new connections. Listening插座( s点击这里)只能接受新的连接。 By definition it does not have the other end to exchange data with. 根据定义,它没有另一端可以交换数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM