a3b18ab931fc908fb70a1b370c154f4e00e6e2ff
[mudpy.git] / 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 import muffuniv
12 for module in muff.__all__:
13         exec("import " + module)
14
15 def check_for_connection(newsocket):
16         """Check for a waiting connection and return a new user object."""
17
18         # try to accept a new connection
19         try:
20                 connection, address = newsocket.accept()
21         except:
22                 return None
23
24         # note that we got one
25         muffmisc.log("Connection from " + address[0])
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((muffuniv.universe.categories["internal"]["network"].get("host"), muffuniv.universe.categories["internal"]["network"].getint("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         muffmisc.log("Waiting for connection(s)...")
64
65         # store this in a globally-accessible place
66         muffvars.newsocket = newsocket
67