Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 服务器无法对整数数组排序并发送到客户端_Python_Arrays_Sockets - Fatal编程技术网

Python 服务器无法对整数数组排序并发送到客户端

Python 服务器无法对整数数组排序并发送到客户端,python,arrays,sockets,Python,Arrays,Sockets,我试图将随机大小的int数组从多个客户端发送到服务器,服务器将不断地将新接收到的int数组添加到全局数组中,并将累计排序的数组返回给客户端。我的客户端代码能够向服务器发送和接收int数组。但服务器无法读取int数组并进行排序并发送回客户端(我的服务器可以读取原始int数组并发送回客户端,但这不是我想要的) 在我的服务器代码中,注释部分不起作用。我是python和socket编程的新手 Client.py # Import socket module import socket, pickle i

我试图将随机大小的int数组从多个客户端发送到服务器,服务器将不断地将新接收到的int数组添加到全局数组中,并将累计排序的数组返回给客户端。我的客户端代码能够向服务器发送和接收int数组。但服务器无法读取int数组并进行排序并发送回客户端(我的服务器可以读取原始int数组并发送回客户端,但这不是我想要的)

在我的服务器代码中,注释部分不起作用。我是python和socket编程的新手

Client.py

# Import socket module
import socket, pickle
import random


def Main():
    # local host IP '127.0.0.1'
    host = '127.0.0.1'

    # Define the port on which you want to connect
    port = 12345

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # connect to server on local computer
    s.connect((host, port))


    while True:

        # Generate Random array to be sent to server
        arr = []
        # Generate random size between 10 and 20
        # random_size = random.randint(10, 20)
        random_size = random.randint(1, 3)

        for i in range(0, random_size):
            arr.append(random.randint(0, 10))
        print('Array = ' + str(arr))

        # Serialise the array to byte stream before sending to server
        data_stream = pickle.dumps(arr)

        #Array byte stream sent to server
        s.send(data_stream)

        # messaga received from server
        data = s.recv(1024)
        #deserialise the byte stream into array after receiving from server
        data_arr = pickle.loads(data)

        # print the received message
        #print('Received', repr(data_arr))
        print('Received from Server: ', data_arr)

        # ask the client whether he wants to continue
        ans = input('\nDo you want to continue(y/n) :')
        if ans == 'y':
            continue
        else:
            break
    # close the connection
    s.close()


if __name__ == '__main__':
    Main()

Server.py

# import socket programming library
import socket, pickle

# import thread module
from _thread import *
import threading
from sortedcontainers import SortedList
import bisect

#Container to store accumulated int array from multiple clients
sl = SortedList()

# To protect
print_lock = threading.Lock()


# thread fuction
def threaded(c):
    while True:

        # data received from client
        data = c.recv(1024)
        # Data from client can't be printed =============== why?
        print(data)
        if not data:
            print('No data received from client - Bye')

            # lock released on exit
            print_lock.release()
            break

        c.send(data)  # ===> It works but I want to add received int array into global sl before sending back to client

        '''        
        ////////////////////// Code in this comment section is not working //////////////////
        #Deserialise Byte stream array from client into array list
        data_arr = pickle.loads(data)

        #Add received int array from client to global sortedList sl in sorted order
        for i in data_arr:
            bisect.insort(sl, i)
            sl.add(i)
        print(sl)

        #Serialise sorted sl into Byte stream before sending to client
        data_stream = pickle.dumps(sl)

        # send back sorted integer list to client
        c.send(data_stream)
        '''

    # connection will never be closed, server will run always
    #c.close()


def Main():
    host = ""

    # We can use a port on our specific computer
    # But in this case it is 12345 (it can be anything)
    port = 12345
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    print("socket binded to post", port)

    # put the socket into listening mode
    s.listen(5)
    print("socket is listening")

    # a forever loop until client wants to exit
    while True:
        # establish connection with client
        c, addr = s.accept()

        # lock acquired by client
        print_lock.acquire()
        print('Connected to :', addr[0], ':', addr[1])

        # Start a new thread and return its identifier
        start_new_thread(threaded, (c,))
    s.close()


if __name__ == '__main__':
    Main()

我在终端运行它,我看到了错误

NotImplementedError: use ``sl.add(value)`` instead
但这似乎是一个不完整的信息

移除后

bisect.insort(sl, i)
它开始工作了


可能有:
使用``sl.add(value)``而不是``bisect.insort(sl,i)`

在终端/控制台/cmd.exe中运行服务器时是否出现错误?不,从pycharm运行服务器时未出现任何错误当我在终端/控制台中运行服务器时,则出现错误
未实现错误:使用``sl.add(value)``相反
>直接在终端中运行,而不是在PyCharm中运行。什么是“不工作”呢?制作一个具有预期与实际输出的可复制示例,并对任何错误消息进行完整回溯。阅读此外,套接字也不是基于消息的
recv(1024)
可以接收0(套接字关闭)或1-1024字节。这些可能是前一次发送的一部分,甚至是两次不同发送的一部分。您所知道的是,您以相同的顺序发送字节。你必须设计一个协议来确保你有一个完整的消息。用一个特殊的字节或序列来分隔消息,首先发送消息的大小,等等@MarkTolonen有了这个想法,但是对于像我这样的小整数数组,我相信它应该可以工作。感谢您提醒Hanks它很有效,我忘了删除我尝试用于普通列表的bisect.insort()。你知道在带对分的列表中,哪一个更有效吗?我不知道哪一个更有效。我第一次看到两个。您可以使用大量随机数据和检查时间来运行两者。