套接字服务器 - 如何在不阻塞的情况下执行recv

时间:2018-01-21 18:45:48

标签: python sockets

我正在按照学校的规则创建套接字服务器。 我必须添加选项 - 检查客户端是否有recv。 client_socket.recv在这里不是一个选项,因为它的阻塞,我的目标是在没有阻塞的情况下recv,只有当我获取数据时。

我知道如何检查服务器中是否有recv,但我在客户端做同样的事情并不成功。

服务器:

import socket
import select


#python.exe C:\Users\Yannay\PycharmProjects\serveralot\Server.py


def send_waiting_messages(wlist, sendMsg):
#get list of open sockets

    for msg in sendMsg:
        (client_socket, data) = msg

        if client_socket in wlist:
            client_socket.send(data)
            sendMsg.remove(msg)






server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 13))
server_socket.listen(5)

open_client_sockets = []
sendMsg = []


while True:

    #get lists of clients
    rlist, wlist, xlist = select.select([server_socket] + open_client_sockets, open_client_sockets, [])

    for s in rlist:
        if s is server_socket:
            (new_socket, address) = server_socket.accept()
            open_client_sockets.append(new_socket)



        else:
            try:
                data = s.recv(1024)
            except:
                open_client_sockets.remove(s)
                continue


            #when client disconnecting he sends "" to the server - he sends nothing
            if data == "" or data == "exit":
                open_client_sockets.remove(s)
                sendMsg = [item for item in sendMsg if item[0] != s]

                print "Connection with client closed \n"
            else:
                sendMsg.append((s, "Hello, " + data))

                print "New data from client: "
                print data + "\n"


    send_waiting_messages(wlist, sendMsg)



server_socket.close()

客户端:

from __future__ import print_function
#this import lets me do print and then another print with no space between those prints


#python.exe C:\Users\Yannay\PycharmProjects\serveralot\Client.py


import msvcrt
import socket
import select


client_socket = socket.socket()
client_socket.connect(('127.0.0.1', 13))

client_socket.recv

data = ""

print ("Please write a message to the server \n")


data = ""



while True:

    if msvcrt.kbhit:
        letter = msvcrt.getch()


        if letter != "\r":
            data += letter
            print (data[-1], end='')


        elif data == "exit":
            break



        elif len(data) > 0:

            print ("")

            #here need to check if received data from the server - and print this data


            client_socket.send(data)


            data = ""


        else:
            data = ""

            #here need to check if received data from the server - and print this data






client_socket.close()

感谢您的帮助!!

0 个答案:

没有答案