source: trigger/TestClient3.py@ 63

Last change on this file since 63 was 52, checked in by rissim, 15 years ago
trigger software (VME) v1
  • 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 # Contains client address, set it
40 addr = data.split('CLIENT: ')[1]
41 self.prompt = '[' + '@'.join((self.name, addr)) + ']> '
42 except socket.error, e:
43 print 'Could not connect to chat server @%d' % self.port
44 sys.exit(1)
45
46 def cmdloop(self):
47
48 while not self.flag:
49 try:
50 sys.stdout.write(self.prompt)
51 sys.stdout.flush()
52
53 # Wait for input from stdin & socket
54 inputready, outputready,exceptrdy = select.select([0, self.sock], [],[])
55
56 for i in inputready:
57 if i == 0:
58 data = sys.stdin.readline().strip()
59 if data: send(self.sock, data)
60 elif i == self.sock:
61 data = receive(self.sock)
62 if not data:
63 print 'Shutting down.'
64 self.flag = True
65 break
66 else:
67 sys.stdout.write(data + '\n')
68 sys.stdout.flush()
69
70 except KeyboardInterrupt:
71 print 'Interrupted.'
72 self.sock.close()
73 break
74
75
76if __name__ == "__main__":
77 import sys
78
79 if len(sys.argv)<3:
80 sys.exit('Usage: %s chatid host portno' % sys.argv[0])
81
82 client = ChatClient(sys.argv[1],sys.argv[2], int(sys.argv[3]))
83 client.cmdloop()
84
Note: See TracBrowser for help on using the repository browser.