多进程TCP服务器

概述

实现了一个TCP服务器,该服务器可以使用预分叉工作者模型同时处理多个客户端。服务器提供对象识别功能,即客户端将向服务器发送图像,服务器将尝试识别图片内部的内容并将答案发送回客户端。

服务器体系结构:
多进程TCP服务器_第1张图片

代码如下:

server.py

import os
import sys
import socket
import random
import shutil
import logging
import numpy as np
import urllib.request
import multiprocessing
from multiprocessing import Process
from concurrent.futures import ThreadPoolExecutor
from keras_squeezenet import SqueezeNet
from keras.preprocessing import image
from keras.applications.imagenet_utils import preprocess_input
from keras.applications.imagenet_utils import decode_predictions

os.environ["TF_CPP_MIN_LOG_LEVEL"]="3"

#portNum = int(sys.argv[1])
portNum = 50002
#processNum = int(sys.argv[2])
processNum = 4

#create a logger with the program name and the level = DEBUG
logger = logging.getLogger(__name__)
#logger.setLevel(logging.DEBUG)

# set up logging to file
logging.basicConfig(
    format='[%(asctime)s] [%(levelname)s] [%(processName)s] [%(threadName)s] : %(message)s',
    level=logging.INFO)

#create a handler that will write log to stderr
file_handler = logging.FileHandler("server_log.txt")
file_handler.setLevel(logging.INFO)

logger.addHandler(file_handler)

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("localhost", portNum))
logger.info(("Start listening for connections on port {0!s}").format(portNum))
server_socket.listen(10)

socket_queue = multiprocessing.Queue()

def ThreadFunction(socket_queue,locker):
    executor = ThreadPoolExecutor(max_workers=4)
    while True:
        locker.acquire()
        # In the new process, recover the socket from the queue
        client_info = socket_queue.get()
        locker.release()
        # Submit a target function 'serve_client' with arguments to
        # the executor (note we cannot use the subclass defined above)
        executor.submit(ObejectRecognition,client_info)

def ObejectRecognition(client_info):
    client_socket = client_info[0]
    address = client_info[1]
    whole_url = ""
    while True:
        # Read data from client
        url = client_socket.recv(2048)
        logger.info(("Received Client {0!s}.").format(address))

        url = url.decode("utf-8")
        # if receive something,continue
        if (url != ""):
            # if receive [END],break
            if ("[END]" in url):
                whole_url = whole_url + url
                break
            else:
                whole_url = whole_url + url
        else:
            logger.info("Connection failed.")

    fileName = "images" + str(random.randint(1, 10000001)) + ".jpg"

    if(len(whole_url)!=0):
        whole_url = whole_url.rstrip("[END]")
        logger.info(("Client submitted URL {0!s}").format(whole_url))
        urllib.request.urlretrieve(whole_url, fileName)
        oldPath = os.getcwd() + "/" + fileName
        newPath = os.getcwd() + "/images/" + fileName
        shutil.move(oldPath, newPath)
        logger.info(("Image saved to images/{0!s}").format(fileName))

        model = SqueezeNet()
        img = image.load_img(newPath, target_size=(227, 227))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)
        preds = model.predict(x)
        result = decode_predictions(preds)
        most_probable = result[0][0]
        predict_data = (most_probable[1], most_probable[2])
        logger.info(("SqueezeNet result: {0!s}").format(predict_data))

        if(len(predict_data)!=0):
            send_data = predict_data[0] + "," +str(predict_data[1])
            send_data = send_data.encode("utf-8")
            client_socket.sendall(send_data)
        else:
            logger.info("Empty result data!")

    # Close the socket
    logger.info("Client connection closed.")
    client_socket.shutdown()
    client_socket.close()



if __name__ == '__main__':
    processes = []
    locker = multiprocessing.Lock()
    # create the specific number of child processes
    for i in range(processNum):
        child_process = Process(target=ThreadFunction, args=(socket_queue,locker,))
        logger.info(("Created process {0!s}").format(child_process.name))
        child_process.start()
        processes.append(child_process)
    while True:
        # accept connections from outside
        (client_socket, address) = server_socket.accept()
        logger.info(("Client {0!s} connected.").format(address))
        # handle = multiprocessing.reduction.reduce_socket(client_socket)
        submitObj = []
        submitObj.append(client_socket)
        submitObj.append(address)
        socket_queue.put(submitObj)

client.py

import socket
import sys
import logging

#ipAddress = sys.argv[1]
#portNum = int(sys.argv[2])
#url = sys.argv[3]
ipAddress = "localhost"
portNum = 50002
#url = "https://media1.britannica.com/eb-media/57/93557-004-13E80176.jpg"
#url = "https://www.natgeokids.com/wp-content/uploads/2014/04/panda-facts-5.jpg"
url = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUSEhAVFRUV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nO/P5oZw8nNZJ4u0U2tK5Tm5ulXK/u3QyV8YkdpH2c094Wyx2pvTtWLi4LWYsw/Rmkjl8FmWxi9RW39y/CT+DNIxTtUknnMri0CjgCK4kkqMuywJJJJKcdXEkkzOEkkklOOhExpJJ10cObqnMSSXHEib9YeBSSROJQkupInGy9kB/4tT/5v+y9fR9R2T4JJKGfYyPLenf98H+BH/uSqiCSS3dP9KP4KFvrYgvUegJ/sbPvSf6kklDr/pfv/sfT+o8h9uf/AFBn+CP9b150kksyPRbfZwrnJdSTCnSuSdkeP4pJJWEdScEq3gkkrkPpEMvUS4f22+K3HSUf2VvgPkkks+/61X5LlX05/g85k1KSSS0Ckf/Z"

#create a logger with the program name and the level = DEBUG
logger = logging.getLogger(__name__)

# set up logging to file
logging.basicConfig(
    format='[%(asctime)s] [%(levelname)s] [%(processName)s] [%(threadName)s] : %(message)s',
    level=logging.INFO)

#create a handler that will write log to stderr
file_handler = logging.FileHandler("client_log.txt")
file_handler.setLevel(logging.INFO)
logger.addHandler(file_handler)

# create an INET TCP socket
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect to the server (change localhost to an IP address if necessary)
try:
    soc.connect((ipAddress, portNum))
    logger.info(("Connected to server at ({0!s}, {1!s})").format(ipAddress, portNum))
    # Send url to the server
    url = url + "[END]"
    url = url.encode("utf-8")
    soc.send(url)
    logger.info("URL sent to the server")

except:
    logger.info(("Cannot connect to server at {0!s},{1!s}").format(ipAddress, portNum))

while True:
    receive_data = soc.recv(2048)
    receive_data = receive_data.decode("utf-8")
    if (receive_data == ""):
        break
    else:
        tup = receive_data.split(",")
        logger.info("Server response:" + str(tup))

# Always close the socket after use
soc.close()

你可能感兴趣的:(小项目)