-1

我是python套接字编程的新手,我想知道是否有一个我可以使用的网络框架,一旦客户端连接就可以发出一个事件。例如,一旦客户端连接,就可以运行一些代码。这个简单我正在使用的代码

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 7654                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

编辑:

找到异步http://docs.python.org/2/library/asyncore.html#module-asyncore

4

1 回答 1

0

实际上这仅在套接字中相当简单

import socket
s = socket.socket()
host = socket.gethostname()
port = 7654

s.bind((host,port)) #bind the host/port to the server
s.listen(1024) #put the server into listening mode

client, address = s.accept()
print "a client has connected "+str(address)
onConnect(client) #this function is fired when a client connects (and uses the client object as arg

while 1:
    data=client.recv(1024) #receives the data
    if data == None:
        break #breaks when empty data is being received (the client may have disconnected)
    print data #debug reasons

print "The client has disconnected "+str(address)

onDisconnect(client) #this function is fired when a client disconnects

您仍然需要创建 onConnect 和 onDisconnect 函数

于 2013-07-23T11:13:37.817 回答