通过TCP套接字发送文件

时间:2016-02-12 13:34:48

标签: python sockets tcp

我是编程初学者 我有一个程序,通过web中的python中的TCP套接字发送.wav文件。程序运行正常,但我有疑问。在服务器和客户端之间完成传输时,服务器端的程序仍在运行。有没有办法“杀了他”?我的意思是在转移完成后,程序将自行结束。 抱歉英语不好。 这是代码:

import socket                   # Import socket module
import os

port = 60001                  # Reserve a port for your service.
s = socket.socket()             # Create a socket object
host = socket.gethostname()


# Get local machine name
s.bind((host, port))
f = open('fare.wav', 'wb')
# Bind to the port
s.listen(1)                     # Now wait for client connection.

print 'Server listening....'

while True:
    conn, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    print "Recieving..."
    l = conn.recv(4096)
    while (l):
       print "Recieving..."
       f.write(l)
       l = conn.recv(4096)
    f.close()
    print('Done receiving')
    conn.send('Thank you for connecting')
    conn.close()

客户端:

import os
import socket
s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 60001 # Reserve a port for your service.

s.connect((host, port))

f = open('fanfare2.wav','rb')
print("Sending...")
l = f.read(4096)
while (l):
    print("Sending...")
    s.send(l)
    l = f.read(4096)
f.close()
print("Done Sending")
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()

1 个答案:

答案 0 :(得分:0)

如果您不希望在完成交易后关闭它,只需使用break来退出服务器代码的while循环,请同时查看this post

#!/usr/bin/python

import socket                   # Import socket module
import os

port = 60001                  # Reserve a port for your service.
s = socket.socket()             # Create a socket object
host = socket.gethostname()


# Get local machine name
s.bind((host, port))
f = open('fare.wav', 'wb')
# Bind to the port
s.listen(1)                     # Now wait for client connection.

print 'Server listening....'

while True:
    conn, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    print "Recieving..."
    l = conn.recv(4096)
    while (l):
       print "Recieving..."
       f.write(l)
       l = conn.recv(4096)
    f.close()
    print('Done receiving')
    conn.send('Thank you for connecting')
    conn.close()
    break