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 pathPythonChatClient.py
More file actions
Latest commit
106 lines (92 loc) · 3.79 KB
/
Copy pathPythonChatClient.py
File metadata and controls
106 lines (92 loc) · 3.79 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
#!/usr/bin/python
importsocket
importselect
importsys
importos
fromthreadingimportThread
defbinery(string):
"""Convert """
result=tuple(' '.join(format(ord(x), 'b') forxinstring).split())
result=string.encode()
returnresult
defb(string):returnstring.encode()
defd(Bytes):returnBytes.decode()
classChatClient:
"""run with the following commands
cd C:\\Users\\Joshua Bowe\\Downloads\\python code downloaded\\Chapter 16
python PythonChatClient.py 127.0.0.1 20000 joshb"""
def__init__(self, host, port, nickname):
self.socket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((host, port))
self.input=self.socket.makefile('rb', 0)
self.output=self.socket.makefile('wb', 0)
#Send the given nickname to the server.
authenticationDemand=self.input.readline()
print(d(authenticationDemand))
ifnotauthenticationDemand[:12]==binery("Who are you?"):
raiseException ("This doesn't seem to be a Python Chat Server.")
self.output.write(b(nickname+'\r\n'))
response=self.input.readline().strip()
## print(response,type(response))##Testing
ifnotd(response).startswith("Hello"):
raiseException (response)
print(d(response))
#Start out by printing out the list of members.
self.output.write(b'/names\r\n')
print("Currently in the chat room: \n\t", d(self.input.readline().strip()))
self.run()
defrun(self):
"""Start a separate thread to gather the input from the
keyboard even as we wait for messages to come over the
network. This makes it possible for the user to simultaneously
send and receive chat text."""
propagateStandardInput=self.PropagateStandardInput(self.output)
propagateStandardInput.start()
#Read from the network and print everything received to standard
#output. Once data stops coming in from the network, it means
#we've disconnected.
inputText=True
whileinputText:
inputText=self.input.readline()
ifinputText:
print(d(inputText.strip()))
propagateStandardInput.done=True
classPropagateStandardInput(Thread):
"""A class that mirrors standard input to the chat server
until it's told to stop."""
def__init__(self, output):
"""Make this thread a daemon thread, so that if the Python
interpreter needs to quit it won't be held up waiting for this
thread to die."""
Thread.__init__(self)
self.setDaemon(True)
self.output=output
self.done=False
defrun(self):
"Echo standard input to the chat server until told to stop."
whilenotself.done:
inputText=sys.stdin.readline().strip()
ifinputText:
self.output.write(b(inputText+'\r\n'))
if__name__=='__main__':
importsys
#See if the user has an OS-provided 'username' we can use as a default
#chat nickname. If not, they have to specify a nickname.
try:
importpwd
defaultNickname=pwd.getpwuid(os.getuid())[0]
exceptImportError:
defaultNickname=None
iflen(sys.argv) <3ornotdefaultNicknameandlen(sys.argv) <4:
print('Usage: %s [hostname] [port number] [username]'%sys.argv[0])
sys.exit(1)
hostname=sys.argv[1]
port=int(sys.argv[2])
iflen(sys.argv) >3:
nickname=sys.argv[3]
else:
#We must be on a system with usernames, or we would have
#exited earlier.
nickname=defaultNickname
ChatClient(hostname, port, nickname)
## josh = ChatClient('127.0.0.1',20000,'joshb')