forked from schedutron/CPAP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mt_duplex_chat_serv.py
64 lines (52 loc) · 1.91 KB
/
mt_duplex_chat_serv.py
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
#!usr/bin/env python
from __future__ import print_function
from socket import *
import sys
from threading import Thread
class ChatServer():
def __init__(self, host, port, bufsiz):
self.HOST = host
self.PORT = port
self.BUFSIZ = bufsiz
self.ADDR = (host, port)
self.chatServSock = socket(AF_INET, SOCK_STREAM)
self.chatServSock.bind(self.ADDR)
self.msg = ""
self.your_msg = ""
self.connected = False
self.recv_thread = Thread(target=self.get_msg, args=tuple())
self.raw_input_thread = Thread(target=self.get_your_msg)
def get_msg(self):
while 1:
self.msg = self.chatCliSock.recv(self.BUFSIZ)
if self.msg == "quit()":
print("\t\tClient left the chat.\n")
self.connected = False
break
print("\r\t\tClient:", self.msg)
print("-|")
def get_your_msg(self):
while self.connected:
while self.your_msg == "":
self.your_msg = raw_input("-|\n")
self.chatCliSock.send(self.your_msg)
if self.your_msg == 'quit()':
self.connected = False
break
self.your_msg = ""
def run(self):
self.chatServSock.listen(1) # num can be passed to __init__
while True:
print("Waiting for connection...")
self.chatCliSock, self.cliAddr = self.chatServSock.accept()
self.chatCliSock.send('Connection established. Now we can chat!')
self.connected = True
print("Connected to:", self.cliAddr)
self.recv_thread.start()
self.raw_input_thread.start()
self.recv_thread.join()
self.raw_input_thread.join()
self.chatServSock.close() #not really used
if __name__ == '__main__':
chatServer = ChatServer('', 33000, 1024)
chatServer.run()