Imported from archive.
[mudpy.git] / lib / muff / muffsock.py
1 """Socket objects for the MUFF Engine"""
2
3 # Copyright (c) 2005 mudpy, Jeremy Stanley <fungi@yuggoth.org>, all rights reserved.
4 # Licensed per terms in the LICENSE file distributed with this software.
5
6 # need socket.socket for new connection objects and the server's listener
7 import socket
8
9 # hack to load all modules in the muff package
10 import muff
11 for module in muff.__all__:
12         exec("import " + module)
13
14 def check_for_connection(newsocket):
15         """Check for a waiting connection and return a new user object."""
16
17         # try to accept a new connection
18         try:
19                 connection, address = newsocket.accept()
20         except:
21                 return None
22
23         # note that we got one
24         # TODO: we should log this crap somewhere
25         print "Connection from", address
26
27         # disable blocking so we can proceed whether or not we can send/receive
28         connection.setblocking(0)
29
30         # create a new user object
31         user = muffuser.User();
32
33         # associate this connection with it
34         user.connection = connection
35
36         # set the user's ipa from the connection's ipa
37         user.address = address[0]
38
39         # return the new user object
40         return user
41
42 def initialize_server_socket():
43         """Create and open the listening socket."""
44
45         # create a new ipv4 stream-type socket object
46         newsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
47
48         # set the socket options to allow existing open ones to be reused
49         # (fixes a bug where the server can't bind for a minute when restarting
50         # on linux systems)
51         newsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
52
53         # bind the socket to to our desired server ipa and port
54         newsocket.bind((muffconf.config_data.get("network", "host"), muffconf.config_data.getint("network", "port")))
55
56         # disable blocking so we can proceed whether or not we can send/receive
57         newsocket.setblocking(0)
58
59         # start listening on the socket
60         newsocket.listen(1)
61
62         # note that we're now ready for user connections
63         # TODO: we should log this crap somewhere
64         print "Waiting for connection(s)..."
65
66         # store this in a globally-accessible place
67         muffvars.newsocket = newsocket
68
69 def destroy_all_sockets():
70         """Go through all connected users and close their sockets."""
71
72         # note that we're closing all sockets
73         # TODO: we should log this crap somewhere
74         print "Closing remaining connections..."
75
76         # iterate over each connected user and close their associated sockets
77         for user in muffvars.userlist:
78                 user.connection.close()
79