【问题标题】:how to combine server and client to work together as one program?如何将服务器和客户端结合为一个程序一起工作?
【发布时间】:2017-05-18 22:32:00
【问题描述】:

他们的功能是我可以检查是否有传入连接到服务器(在 While 循环内)?

import socket
import sys

HOST = ''   
PORT = 8888 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

while 1:

    ##### IF there is request to server Do #####
          conn, addr = s.accept()
          print 'Connected with ' + addr[0] + ':' + str(addr[1])

          data = conn.recv(1024)
          reply = 'OK...' + data
          conn.sendall(reply)

    ##### Else Do something else like print for example #####
          print 'Nothing yet'
conn.close()
s.close()

我想做的是检查是否没有对我的服务器的请求,我会做其他事情。 可以这样做吗?

【问题讨论】:

    标签: python python-2.7 python-3.x sockets server


    【解决方案1】:

    是的,有这样的功能。

    来自man accept:

    为了在套接字上收到传入连接的通知,您可以 使用 select(2)、poll(2) 或 epoll(7)。一个可读的事件将是 尝试新连接时交付,然后您可以调用 accept() 为该连接获取一个套接字。

    在python中你可以使用select结合超时参数:

    import select
    
    # somewhere in a while loop
    timeout = 0
    incoming_connections, _, __ = select.select([s], [], [], timeout)
    if incoming_connections:
        conn, addr = s.accept()
        ...
    else:
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多