TD2: Ensure chat clients will not send empty message.
[TD_SR.git] / TD2 / client / ThreadClientoSend.java
1 import java.io.*;
2 import java.util.Calendar;
3 import java.util.Random;
4
5 public class ThreadClientoSend implements Runnable {
6 private SocketClient client;
7 //FIXME: use a random name by thread for now, should be setable
8 private String randName;
9
10 ThreadClientoSend(SocketClient c) {
11 client = c;
12 randName = randomName();
13 }
14
15 private String randomName() {
16
17 int leftLimit = 97; // letter 'a'
18 int rightLimit = 122; // letter 'z'
19 int targetStringLength = 8;
20 Random random = new Random();
21 StringBuilder buffer = new StringBuilder(targetStringLength);
22 for (int i = 0; i < targetStringLength; i++) {
23 int randomLimitedInt = leftLimit + (int)(random.nextFloat() * (rightLimit - leftLimit + 1));
24 buffer.append((char)randomLimitedInt);
25 }
26 String generatedString = buffer.toString();
27
28 return generatedString;
29 }
30
31 public void run() {
32 BufferedReader userInput = null;
33 try {
34 userInput = new BufferedReader(new InputStreamReader(System.in));
35 boolean end = false;
36 while (!end) {
37 String line = userInput.readLine();
38 if (line.equals(".")) {
39 end = true;
40 }
41 if (line.length() != 0) {
42 Message oMsg = new Message(randName, line, Calendar.getInstance());
43 client.sendoMsg(oMsg);
44 System.out.println(Thread.currentThread().getName() + " a envoye " + oMsg);
45 }
46 }
47 }
48 catch (IOException e) {
49 System.err.println("IOException: " + e);
50 e.printStackTrace();
51 }
52 finally {
53 if (userInput != null) {
54 try {
55 userInput.close();
56 }
57 catch (IOException e) {
58 System.err.println("IOException: " + e);
59 e.printStackTrace();
60 }
61 }
62 }
63 }
64 }