套接字无法在Python中连接

时间:2014-01-22 15:03:44

标签: python sockets connection

我的代码出了问题 连接应该可以工作,但服务器没有得到任何东西,即使我正在发送数据。

你能看看我的代码并帮助我吗?

import socket

def inviare(ip,port):
    file_name = raw_input("File name? ")
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect((ip,port))
    file_open = open(file_name,"r")
    file_content = file_open.read()
    print file_content
    sock.send(file_content)
    file_open.close()
    sock.close()

def ricevere(ip,port):
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind((ip,port))
    sock.listen(5)
    while 1:
        (connection, adress) = sock.accept()

        try:
            file_data = sock.recv(6000)
            filewrite = open("Down.txt","w")
            print file_data.read()
            filewrite.write(file_data.readlines())
            filewrite.close
        except:
            pass

def main():
    command = raw_input("Send or receive? ");
    if(command == "receive"):
        ip = raw_input("Ip ")
        port = input("Port ")
        ricevere(ip,port)

    elif(command == "send"):

        ip = raw_input("Ip ?")
        port = input("Port?")
        inviare(ip,port)

if __name__ == '__main__':
    main()

我试过在几台机器上运行它并改变了很多东西,但什么都没发生。同样的问题,但它不会输出任何错误!

1 个答案:

答案 0 :(得分:0)

ricevere内部,您尝试从服务器套接字(sock)读取,而不是从已连接的客户端connection读取。

因此它提出了:[Errno 107] Transport endpoint is not connected

(如果您没有传递except子句,但实际上打印了异常,则可以看到。)

当您将try-block更改为:

时,您的脚本会按预期运行
        file_data = connection.recv(6000)
        filewrite = open("Down.txt","w")
        print file_data
        filewrite.write(file_data)
        filewrite.close()