客户端连接或断开与服务器连接后发出事件

时间:2013-07-23 08:20:09

标签: python

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

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

修改

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

1 个答案:

答案 0 :(得分: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函数