Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.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_Python 3.x_Sockets_Network Programming_Client Server - Fatal编程技术网

Python套接字-在循环中接收数据

Python套接字-在循环中接收数据,python,python-3.x,sockets,network-programming,client-server,Python,Python 3.x,Sockets,Network Programming,Client Server,我有一个代理服务器和客户端应用程序。如果缓存中尚未找到请求,服务器将向端口80发出HTTP请求请求。但是,此过程将需要几分钟的时间来获取。并且,在端口80发送数据后,代理服务器将以循环的方式将其发送到客户端。这意味着,客户端还必须在循环中接收数据。但是,如何让客户端等待服务器响应(这可能需要几分钟) 我的代理服务器代码: from Proxy_Cache_DS import * import socket import sys import _thread import datetime imp

我有一个代理服务器和客户端应用程序。如果缓存中尚未找到请求,服务器将向端口80发出HTTP请求请求。但是,此过程将需要几分钟的时间来获取。并且,在端口80发送数据后,代理服务器将以循环的方式将其发送到客户端。这意味着,客户端还必须在循环中接收数据。但是,如何让客户端等待服务器响应(这可能需要几分钟)

我的代理服务器代码:

from Proxy_Cache_DS import *
import socket
import sys
import _thread
import datetime
import os
import pickle


cache = LFUCache(3);


def cache_fn(messageString, client_socket):
    
    print('Connected Accepted')
    
    HttpTypeMethod = messageString[0]
    URLpath = messageString[1]
    URLpath = URLpath[7:]
    
    
    print("Request is ", HttpTypeMethod, " to URL : ", URLpath)
    print("--------------------------------------------------")
    
    
    #start = datetime.datetime.now()
    current_file = "/" + URLpath + ".txt"
    print(current_file[1:])
    try:
        #Search in the cache file
        file = open(current_file[1:], "r")
        contents = file.readlines()
        print("Match found in cache and reading the file\n")
        
        cache.insertItem(URLpath)
        print_cache(cache)
        
        for i in range(0, len(contents)):
            client_socket.send(contents[i].encode())
            
        #print("Time taken to read from Cache:",datetime.datetime.now() - start , " Secs")
    
    except IOError:
        #Fetch from the main server at port 80
        #start = datetime.datetime.now()
        print("Cache File not Found\n File is being fetched from Server to Create Cache\n")
       
        Proxy_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host_url = URLpath
        print(host_url)
        try:
            Proxy_server.connect((host_url, 80))
            cache.insertItem(URLpath)
            save_object(cache)
            print_cache(cache)
            print("Socket Connected on default Port 80 to fetch")
            ser_cache_file = Proxy_server.makefile('rwb', 0)
            
            ser_cache_file.write(bytes("GET " + "/ HTTP/1.1\r\nHost:"+ URLpath +"\r\n\r\n",encoding='utf8'))           
            br = ser_cache_file.readlines()
            
            print(br)
            temp = open("./" + URLpath +'.txt', "w")
      
            for dt in br:
                temp.write(str(dt))
                client_socket.send(dt)
            
        except:
            print("Not a  Valid URL/ Data Could not be written to file")
        #print("Time taken to read from Server:",datetime.datetime.now() - start," Secs")
    print('Written data to file')
    client_socket.close()

def save_object(obj):
    try:
        os.remove('cache.pkl')
        # print("try save")
    except:
        print("Creating cache file")
        # print("except save")
    with open('cache.pkl', 'wb') as output:
            pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)


def main():
    
        try:
            global cache
            with open('cache.pkl', 'rb') as input:
                cache = pickle.load(input)
                print_cache(cache)
        
        except:
            print("Cache file doesn't exist. It is yet to be created")
        port_server = 8055
            
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # server socket
        print("Server is started")
        server_socket.bind(('192.168.1.44', port_server))
        server_socket.listen(5)
        while True:
            print("Bind Successful")
            print("-------------------------------------")
            client_socket, addr = server_socket.accept() 
            print("Received Connection from <Host,Port> ", addr)
            message = client_socket.recv(5000).decode()
            
           
            messageString = str(message).split()
            if len(messageString) <= 1 or len(messageString) > 2:
                
                d = "HTTP/1.1 200 OK\r\n"
                d += "Content-Type: text/html; charset=utf-8\r\n"
                d += "\r\n"
                d += "<html><body>Hello World</body></html>\r\n\r\n"
                client_socket.sendall(d.encode())
                client_socket.shutdown(socket.SHUT_RDWR)
                continue        
            
            _thread.start_new_thread(cache_fn ,(messageString, client_socket))
            client_socket.shutdown(socket.SHUT_RDWR)

if __name__ == '__main__':
    main()

在当前设置中,客户端无法接收任何数据。它只是不停地运行

有人能告诉我如何让客户机等待来自服务器的数据,一旦数据开始传入,它就会在循环中不断接收数据,当服务器没有更多数据时停止接收数据吗

这似乎是一项简单的任务,但我无法让它工作

更新:我解决了。服务器中存在以下问题:

_thread.start_new_thread(cache_fn ,(messageString, client_socket))
client_socket.shutdown(socket.SHUT_RDWR)    <--

\u thread.start\u new\u thread(缓存\u fn,(消息字符串,客户端\u套接字))
客户端套接字关闭(套接字关闭)
_thread.start_new_thread(cache_fn ,(messageString, client_socket))
client_socket.shutdown(socket.SHUT_RDWR)    <--