View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * 
4    * Copyright (C) 1999-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  package chapter4.socket;
11  
12  
13  import java.io.BufferedReader;
14  import java.io.InputStreamReader;
15  
16  import org.slf4j.LoggerFactory;
17  
18  import ch.qos.logback.classic.Logger;
19  import ch.qos.logback.classic.LoggerContext;
20  import ch.qos.logback.classic.net.SocketAppender;
21  
22  
23  /**
24   * This application uses a SocketAppender that log messages to a
25   * server on a host and port specified by the user. It waits for the
26   * user to type a message which will be sent to the server.
27   * */
28  public class SocketClient1 {
29    static void usage(String msg) {
30      System.err.println(msg);
31      System.err.println("Usage: java " + SocketClient1.class.getName() +
32        " hostname port\n" + "   hostname the name of the remote log server\n" +
33        "   port (integer) the port number of the server\n");
34      System.exit(1);
35    }
36  
37    static public void main(String[] args) throws Exception {
38      if (args.length != 2) {
39        usage("Wrong number of arguments.");
40      }
41  
42      String hostName = args[0];
43      int port = Integer.parseInt(args[1]);
44  
45      // Create a SocketAppender connected to hostname:port with a
46      // reconnection delay of 10000 seconds.
47      SocketAppender socketAppender = new SocketAppender();
48      socketAppender.setRemoteHost(hostName);
49      socketAppender.setPort(port);
50      socketAppender.setReconnectionDelay(10000);
51      LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
52      socketAppender.setContext(lc);
53  
54      // SocketAppender options become active only after the execution
55      // of the next statement.
56      socketAppender.start();
57  
58      Logger logger = (Logger) LoggerFactory.getLogger(SocketClient1.class);
59      logger.addAppender(socketAppender);
60  
61      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
62  
63      while (true) {
64        System.out.println("Type a message to send to log server at " + hostName +
65          ":" + port + ". Type 'q' to quit.");
66  
67        String s = reader.readLine();
68  
69        if (s.equals("q")) {
70          break;
71        } else {
72          logger.debug(s);
73        }
74      }
75    }
76  }