source: trigger/TestClient3.py@ 4172

Last change on this file since 4172 was 77, checked in by rissim, 15 years ago
trigger: gui added, interface modified
  • Property svn:executable set to *
File size: 2.7 KB
Line 
1#!/usr/bin/python
2#############################################################################
3# The chat client
4#############################################################################
5
6"""
7Simple chat client for the chat server. Defines
8a simple protocol to be used with chatserver.
9
10"""
11
12import socket
13import sys
14import select
15import readline
16from communication import send, receive
17
18BUFSIZ = 1024
19
20class ChatClient(object):
21 """ A simple command line chat client using select """
22
23 def __init__(self, name, host='127.0.0.1', port=3490):
24 self.name = name
25 # Quit flag
26 self.flag = False
27 self.port = int(port)
28 self.host = host
29 # Initial prompt
30 self.prompt='[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> '
31 # Connect to server at port
32 try:
33 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
34 self.sock.connect((host, self.port))
35 print 'Connected to chat server@%d' % self.port
36 # Send my name...
37 send(self.sock,'NAME: ' + self.name)
38 data = receive(self.sock)
39 print data
40 # Contains client address, set it
41 addr = data.split('CLIENT: ')[1]
42 self.prompt = '[' + '@'.join((self.name, addr)) + ']> '
43 except socket.error, e:
44 print 'Could not connect to chat server @%d' % self.port
45 sys.exit(1)
46
47 def cmdloop(self):
48
49 while not self.flag:
50 try:
51 sys.stdout.write(self.prompt)
52 sys.stdout.flush()
53
54 # Wait for input from stdin & socket
55 inputready, outputready,exceptrdy = select.select([0, self.sock], [],[])
56
57 for i in inputready:
58 if i == 0:
59 data = sys.stdin.readline().strip()
60 if data: send(self.sock, data)
61 elif i == self.sock:
62 data = receive(self.sock)
63 if not data:
64 print 'Shutting down.'
65 self.flag = True
66 break
67 else:
68 sys.stdout.write(data + '\n')
69 sys.stdout.flush()
70
71 except KeyboardInterrupt:
72 print 'Interrupted.'
73 self.sock.close()
74 break
75
76
77if __name__ == "__main__":
78 import sys
79
80 if len(sys.argv)<3:
81 sys.exit('Usage: %s chatid host portno' % sys.argv[0])
82
83 client = ChatClient(sys.argv[1],sys.argv[2], int(sys.argv[3]))
84 client.cmdloop()
85
Note: See TracBrowser for help on using the repository browser.