如何使服务器始终使用套接字监听?

时间:2017-09-03 16:57:06

标签: python python-2.7 sockets server

iv构建基本命令服务器:

import socket
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))

message = raw_input("Insert Command\n")
my_socket.send(message)

data = my_socket.recv(1024)
print "Answer Sent: " + data

my_socket.close()

和一个基本客户:

find()

现在我想让服务器一直听命令,直到他得到一个"退出"命令。我没有办法做到这一点,所以我希望你能帮助我。非常感谢!

2 个答案:

答案 0 :(得分:2)

您可以直接运行循环以继续接收来自客户端,直到收到'exit'

import socket
import time
import random

server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8821))

server_socket.listen(1)

(client_socket, client_address) = server_socket.accept()

while True:
    client_input = client_socket.recv(1024).upper()
    if len(client_input) > 4 or len(client_input) < 4:
        client_socket.send("The length of your messege\nneeds to be 4 chracters.\nI know only 4 commands.\nRAND, TIME, NAME & EXIT.\nThanks.")
    else:
        if client_input == 'TIME':
            client_socket.send(time.strftime("%c"))
        elif client_input == 'RAND':
            client_socket.send(str(random.randrange(0, 11)))
        elif client_input == 'NAME':
            client_socket.send("My master called me \"Arik\". Funny, ha?")
        elif client_input == 'EXIT':
            client_socket.send("Exiting.")
            break
        else:
            client_socket.send("Unknown command")

client_socket.close()
server_socket.close()

你的客户应该是:

import socket
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))

message = ''
while message.upper() != 'EXIT':
    message = raw_input("Insert Command\n")
    my_socket.send(message)
    data = my_socket.recv(1024)
    print "Answer Sent: " + data

my_socket.close()

答案 1 :(得分:-1)

我自己从未使用过python网络,但我认为这样可行。 你可以把你的服务器监听器放在一个循环中,如果它接收到EXIT,那么就打破循环。

while(true):
    server_socket.listen(1)

    (client_socket, client_address) = server_socket.accept()

    client_input = client_socket.recv(1024)
    client_input = client_input.upper()


    if client_input == 'TIME':
        client_socket.send(time.strftime("%c"))
    elif client_input == 'RAND':
        client_socket.send(str(random.randrange(0, 11)))
    elif client_input == 'NAME':
        client_socket.send("My master called me \"Arik\". Funny, ha?")
    elif client_input == 'EXIT':
          break;
    else:
        client_socket.send("Unknown command")

    if len(client_input) > 4 or len(client_input) < 4:
        client_socket.send("The length of your messege\nneeds to be 4 chracters.\nI know only 4 commands.\nRAND, TIME, NAME & EXIT.\nThanks.")

client_socket.close()
server_socket.close()