如何使服务器端套接字代码连续运行

时间:2016-04-22 18:46:11

标签: python sockets

我有一个服务器/客户端套接字程序,用于将文件从客户端传输到服务器。问题是一旦文件传输,代码就会停止运行。我想改变它,使服务器端代码持续运行,这样我就可以多次传输文件而无需一次又一次地运行代码

服务器代码:

import socket


host = ''
port = 5560

def setupServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created.")
    try:
        s.bind((host, port))
    except socket.error as msg:
        print(msg)
    print("Socket bind comlete.")
    return s

def setupConnection():
    s.listen(1) # Allows one connection at a time.
    conn, address = s.accept()
    print("Connected to: " + address[0] + ":" + str(address[1]))
    return conn

def storeFile(filePath):
    picFile = open(filePath, 'wb')
    print(filePath)
    print("Opened the file.")
    pic = conn.recv(1024)
    #print(pic)
    while pic:
        print("Receiving picture still.")
        picFile.write(pic)
        pic = conn.recv(1024)
    picFile.close()

def dataTransfer(conn):
    # A big loop that sends/receives data until told not to.
    while True:
        # Receive the data
        data = conn.recv(1024) # receive the data
        data = data.decode('utf-8')
        # Split the data such that you separate the command
        # from the rest of the data.
        dataMessage = data.split(' ', 1)
        command = dataMessage[0]
        if command == 'GET':
            reply = GET()
        elif command == 'REPEAT':
            reply = REPEAT(dataMessage)
        elif command == 'STORE':
            print("Store command received. Time to save a picture")
            storeFile(dataMessage[1])
            reply = "File stored."
        elif command == 'LED_ON':
            callLED()
            reply = 'LED was on'
        else:
            reply = 'Unknown Command'
        # Send the reply back to the client
        conn.sendall(str.encode(reply))
        #print("Data has been sent!")
    conn.close()


s = setupServer()

while True:
    try:
        conn = setupConnection()
        dataTransfer(conn)
    except:
        break 

客户端代码如下:

import socket
from time import sleep
from time import time


host = '192.168.0.17'
port = 5560

data = "hi"
filepath = "/var/www/html/unknown.txt"
def setupSocket():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    return s

def sendPic(s, filePath):
    print(filePath)
    pic = open(filePath, 'rb')
    chunk = pic.read(1024)
    s.send(str.encode("STORE " + filePath))
    t = time()
    while chunk:
        print("Sending Picture")
        s.send(chunk)
        #print(chunk)
        chunk = pic.read(1024)
    pic.close()
    print("Done sending")
    print("Elapsed time = " + str(time() - t) + 's')
    #s.close()
    return "Done sending"

def sendReceive(s, message):
    s.send(str.encode(message))
    reply = s.recv(1024)
    print("We have received a reply")
    print("Send closing message.")
    s.send(str.encode("EXIT"))
    #s.close()
    reply = reply.decode('utf-8')
    return reply

def transmit(message):
    s = setupSocket()
    response = sendReceive(s, message)
    return response

def backup(filePath):
    s = setupSocket()
    response = sendPic(s, filePath)
    return response

while True:
    backup(filepath)
    print("Backup Complete!")
    break

我没有代码。我对从YouTube视频中获得的代码做了一些更改。

1 个答案:

答案 0 :(得分:0)

您是否看过SocketServer模块? 您可以将dataTransfer()函数设置为RequestHandler类的handle()方法,然后使用serve_forever()方法启动服务器。