| 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 | Message oMsg = new Message(randName, line, Calendar.getInstance()); |
| 42 | client.sendoMsg(oMsg); |
| 43 | System.out.println(Thread.currentThread().getName() + " a envoye " + oMsg); |
| 44 | } |
| 45 | } |
| 46 | catch (IOException e) { |
| 47 | System.err.println("IOException: " + e); |
| 48 | e.printStackTrace(); |
| 49 | } |
| 50 | finally { |
| 51 | if (userInput != null) { |
| 52 | try { |
| 53 | userInput.close(); |
| 54 | } |
| 55 | catch (IOException e) { |
| 56 | System.err.println("IOException: " + e); |
| 57 | e.printStackTrace(); |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | } |