Python套接字服务器只获取一次信号

时间:2012-09-08 19:40:33

标签: python sockets

我刚刚进入网络,我想尝试ping一下

服务器代码:

import socket

host = 'localhost'
port = 5050
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
    client, address = s.accept()
    data = client.recv(size)
    print "getting "+str(data)+" from "+ str(address)

客户端代码

import socket
import time

host = 'localhost'
port = 5050
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
while 1:
    s.send('PING')
    print "sending package"
    time.sleep(1)

现在输出:

getting PING from ('127.0.0.1', 56580)

只有一次,而它应该每秒都有一次PING。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

由于您只与服务器建立一个连接,因此您只需拨打.accept()一次即可接受该连接。打开后,套接字将接收您从客户端发送的定期数据包。

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
client, address = s.accept()
while 1:
    data = client.recv(size)
    print "getting "+str(data)+" from "+ str(address)

答案 1 :(得分:0)

嗯,你只读一次。在服务器上的循环中调用client.recv

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while True:
    client, address = s.accept()
    # TODO Use fork(), threading, or async I/O to for parallel processing
    while True: 
        data = client.recv(size)
        print "getting "+str(data)+" from "+ str(address)

或为每个ping创建一个套接字:

while True:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host,port))
    s.send('PING')
    print "sending package"
    time.sleep(1)