套接字和客户端响应

时间:2017-05-28 15:13:51

标签: python sockets server client

现在我需要的是在完成一次尝试后服务器仍然连接, 就像我写了str命令" time"我有时间,仍然可以连接服务器我尝试添加一些"如果"声明并为"选择"输入,但我仍然无法完成这项工作我总是得到空白的响应并与服务器断开连接,谢谢你的帮助,对不起英语。

我需要一些关于此代码的帮助:

import socket
import time

server = socket.socket()
server.bind(('127.0.0.1', 8820))
server.listen(1)
(client_socket, client_address) = server.accept()
client_rq = client_socket.recv(1024)
b = time.ctime()


if client_rq == "name":
    client_socket.send('the server name is london project')

if client_rq == "help":
    client_socket.send('for help with this server connect @gmail.com')

if client_rq == "time":
    client_socket.send(b)

server.close()

这是客户:

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

x = raw_input("choice: ")
client.send(x)
data = client.recv(1024)
print data

client.close()

1 个答案:

答案 0 :(得分:0)

在服务器中循环:

import socket
import time

server = socket.socket()
server.bind(('127.0.0.1', 8820))
server.listen(1)
while True:
    client_socket, client_address = server.accept()
    client_rq = client_socket.recv(1024)
    b = time.ctime()

    if client_rq == "name":
        client_socket.send('the server name is london project')

    if client_rq == "help":
        client_socket.send('for help with this server connect @gmail.com')

    if client_rq == "time":
        client_socket.send(b)

    if client_rq == "quit":
        break # from the loop

server.close()

从客户端发送“quit”以中断循环并退出服务器。