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         muffmisc.log("Connection from " + address[0])
25
26         # disable blocking so we can proceed whether or not we can send/receive
27         connection.setblocking(0)
28
29         # create a new user object
30         user = muffuser.User()
31
32         # associate this connection with it
33         user.connection = connection
34
35         # set the user's ipa from the connection's ipa
36         user.address = address[0]
37
38         # return the new user object
39         return user
40
41 def initialize_server_socket():
42         """Create and open the listening socket."""
43
44         # create a new ipv4 stream-type socket object
45         newsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
46
47         # set the socket options to allow existing open ones to be reused
48         # (fixes a bug where the server can't bind for a minute when restarting
49         # on linux systems)
50         newsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
51
52         # bind the socket to to our desired server ipa and port
53         newsocket.bind((muffconf.get("network", "host"), muffconf.getint("network", "port")))
54
55         # disable blocking so we can proceed whether or not we can send/receive
56         newsocket.setblocking(0)
57
58         # start listening on the socket
59         newsocket.listen(1)
60
61         # note that we're now ready for user connections
62         muffmisc.log("Waiting for connection(s)...")
63
64         # store this in a globally-accessible place
65         muffvars.newsocket = newsocket
66