如何使服务器端socket代码连续运行

2024-09-25 00:27:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个服务器/客户机套接字程序,用于将文件从客户机传输到服务器。一旦代码被传输,问题就会停止运行。我想更改它,使服务器端代码连续运行,这样我就可以多次传输文件,而不必反复运行代码

服务器代码:

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 

客户端代码如下:

^{pr2}$

我不拥有代码。我对从YouTube视频中得到的代码做了一些修改。在


Tags: theto代码服务器dataaddressdefsocket