Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonChatServer.py
More file actions
Latest commit
267 lines (248 loc) · 10.2 KB
/
Copy pathPythonChatServer.py
File metadata and controls
267 lines (248 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/usr/bin/python
# Run with cd C:\Users\Joshua Bowe\Downloads\python code downloaded\Chapter 16
#Then do py PythonChatServer.py 127.0.0.1 20000
# or py -3 PythonChatServer.py 127.0.0.1 8000
importsocketserver
importre
importsocket
importsocketserverasSocketServer
importos
#####STARTING LOG FILE#########
importtime##import time, so you can create the log file for the day
foo=time.asctime().split(' ')
l=[foo[4], foo[1], foo[2]]
defmake_log_name(l):
"""you take in a list. It contains the year, month, and day in that order. It
returns a nicely formatted name"""
f="%s_%s-%s"%(l[0],l[1],l[2])
f=f.replace(':',';')
print(f)
returnf
filen=os.path.join('logs',make_log_name(l))
bar=open(filen,'a')
bar.write("Started server at \"%s\"\n"%time.asctime())
bar.close()
print("Wrote to log file %s"%filen)
defwrite_text(text):
bar=open(filen,'a')
bar.write(text)
bar.close()
delbar
defwrite_p(text,p=0):
ifp==1:print(text)
write_text(text)
delfoo,l,make_log_name,bar
#############END LOG FILE SECTION
defb(string):returnstring.encode()
defd(Bytes):returnBytes.decode()
defjoin(S,it):
foo=""
it=list(it)
foriinrange(len(it)-1):
foo+="%s%s"%(d(it[i]),S)
foo+='%s'%d(it[-1])
returnfoo
##users={'joshb':'Woof!!!','bowej':'!!!fooW'}##Testing
##print(join(', ',users.keys()))##Testing
classClientError(Exception):
"An exception thrown because the client gave bad input to the server."
pass
classPythonChatServer(socketserver.ThreadingTCPServer):
"The server class."
def__init__(self, server_address, RequestHandlerClass):
"""Set up an initially empty mapping between a user's nickname
and the file-like object used to send data to that user."""
SocketServer.ThreadingTCPServer.__init__(self, server_address,
RequestHandlerClass)
self.users= {}
classRequestHandler(SocketServer.StreamRequestHandler):
"""Handles the life cycle of a user's connection to the chat
server: connecting, chatting, running server commands, and
disconnecting."""
NICKNAME=re.compile('^[A-Za-z0-9_-]+$') #Regex for a valid nickname
defhandle(self):
"""Handles a connection: gets the user's nickname, then
processes input from the user until they quit or drop the
connection."""
self.nickname=None
self.privateMessage('Who are you?')
nickname=self._readline()
done=False
try:
self.nickCommand(nickname)
self.privateMessage('Hello %s, welcome to the Python Chat Server.'\
%d(nickname))
self.broadcast('%s has joined the chat.'%d(nickname), False)
exceptClientErroraserror:
self.privateMessage(error.args[0])
done=True
exceptsocket.error:
done=True
## print("\"%s\" has logged in."%d(self.nickname))
write_p("\"%s\" has logged in.\n"%d(self.nickname),1)
#Now they're logged in; let them chat.
whilenotdone:
try:
done=self.processInput()
exceptClientErroraserror:
self.privateMessage(str(error))
exceptsocket.errorase:
done=True
deffinish(self):
"Automatically called when handle() is done."
ifself.nickname:
#The user successfully connected before disconnecting.
#Broadcast that they're quitting to everyone else.
message='%s has quit.'%d(self.nickname)
ifhasattr(self, 'partingWords'):
message='%s has quit: %s'% (d(self.nickname),
self.partingWords)
self.broadcast(message, False)
#Remove the user from the list so we don't keep trying to
#send them messages.
ifself.server.users.get(self.nickname):
write_p("\"%s\" has quit.\n"%d(self.nickname),1)
del(self.server.users[self.nickname])
self.request.shutdown(2)
self.request.close()
defprocessInput(self):
"""Reads a line from the socket input and either runs it as a
command, or broadcasts it as chat text."""
done=False
l=self._readline()
command, arg=self._parseCommand(l)
ifcommand:
done=command(arg)
else:
l='<%s> %s\n'% (d(self.nickname), d(l))
write_p("To all: %s"%l)
self.broadcast(l)
returndone
#Each server command is implemented as a method. The _parseCommand method, defined later, takes a line that looks like /nick and calls the corresponding method (in this case, nickCommand):
#Below are implementations of the server commands.
defnickCommand(self, nickname):
"""Attempts to change a user's nickname.
The new(and not working code is below
if not nickname:
raise ClientError ('No nickname provided.')
## print(self.NICKNAME,type(self.NICKNAME),'\n',
## nickname,type(nickname))#Testing
if type(nickname)==str:nickname.encode()
if type(nickname)==bytes:
if not self.NICKNAME.match(d(nickname)):
raise ClientError ('Invalid nickname: %s' % nickname)
elif type(nickname)==str:
if not self.NICKNAME.match(nickname):
raise ClientError ('Invalid nickname: %s' % nickname)
if nickname == self.nickname:
raise ClientError ('You are already known as %s.' % nickname)
if self.server.users.get(nickname, None):
raise ClientError ('There\'s already a user named "%s" here.' % nickname)
oldNickname = None
if self.nickname:
oldNickname = self.nickname
del(self.server.users[self.nickname])
self.server.users[nickname] = self.wfile
self.nickname = nickname
if oldNickname:"""
ifnotnickname:
raiseClientError ('No nickname provided.')
iftype(nickname)==str:
nickname=b(nickname)
ifnotself.NICKNAME.match(d(nickname)):
raiseClientError ('Invalid nickname: %s'%nickname)
ifnickname==self.nickname:
raiseClientError ('You are already known as %s.'%nickname)
ifself.server.users.get(nickname, None):
raiseClientError ('There\'s already a user named "%s" here.'%nickname)
oldNickname=None
ifself.nickname:
oldNickname=self.nickname
del(self.server.users[self.nickname])
self.server.users[nickname] =self.wfile
self.nickname=nickname
ifoldNickname:
self.broadcast('%s is now known as %s'% (d(oldNickname),
d(self.nickname)))
defquitCommand(self, partingWords):
"""Tells the other users that this user has quit, then makes
sure the handler will close this connection."""
ifpartingWords:
self.partingWords=partingWords
#Returning True makes sure the user will be disconnected.
returnTrue
defnamesCommand(self, ignored):
"Returns a list of the users in this chat room."
user_list=join(', ',self.server.users.keys())
self.privateMessage(user_list)
defmsgCommand(self,nickAndMsg):
"Send a private message to another user"
iftype(nickAndMsg)==Noneortype(nickAndMsg)==type(None):
self.privateMessage("No input given")
return
iflen(nickAndMsg)==0:
self.privateMessage("No input given")
return
ifnot' 'innickAndMsg:
self.privateMessage("No message given, use a space ' ' to give one")
return
nick,msg=nickAndMsg.split(' ',1)
ifnick==self.nickname:
self.privateMessage("What, send a message to yourself?")
return
user=self.server.users.get(b(nick))
## print(user,nick,self.server,self.server.users)
ifnotuser:
self.privateMessage("No such user: '%s'"%nick)
return
msg="[Private from %s] %s\r\n"%(d(self.nickname),msg)
write_p(msg)
## write_p("%s:%s"%(user,type(user)),1)
user.write(b(msg))
return
# Below are helper methods.
defbroadcast(self, message, includeThisUser=True):
"""Send a message to every connected user, possibly exempting the
user who's the cause of the message."""
message=self._ensureNewline(message)
foruser, outputinself.server.users.items():
ifincludeThisUseroruser!=self.nickname:
output.write(b(message))
defprivateMessage(self, message):
"Send a private message to this user."
n=self._ensureNewline(message).encode()
self.wfile.write(n)
def_readline(self):
"Reads a line, removing any whitespace."
returnself.rfile.readline().strip()
def_ensureNewline(self, s):
"Makes sure a string ends in a newline."
ifsands[-1] !='\n':
s+='\r\n'
returns
def_parseCommand(self, i):
"""Try to parse a string as a command to the server. If it's an
implemented command, run the corresponding method."""
i=d(i)
commandMethod, arg=None, None
ifiandi[0] =='/':
iflen(i) <2:
raiseClientError( 'Invalid command: "%s"'%i)
commandAndArg=i[1:].split(' ', 1)
iflen(commandAndArg) ==2:
command, arg=commandAndArg
else:
command, =commandAndArg
commandMethod=getattr(self, command+'Command', None)
ifnotcommandMethod:
raiseClientError( 'No such command: "%s"'%command)
returncommandMethod, arg
if__name__=='__main__':
importsys
## sys.argv.append('127.0.0.1');sys.argv.append('27272')
iflen(sys.argv) <3:
print('Usage: %s [hostname] [port number]'%sys.argv[0])
sys.exit(1)
hostname=sys.argv[1]
port=int(sys.argv[2])
PythonChatServer((hostname, port), RequestHandler).serve_forever()