Binds to a specified port number on the local host and waits for a connection request from a client. Once a connection is established, it operates in one of two modes: download and upload. @author tlmader.dev@gmail.com @since 2017-02-27
| 14 | * @since 2017-02-27 |
| 15 | */ |
| 16 | @SuppressWarnings("JavaDoc") |
| 17 | public class NetcatClient { |
| 18 | |
| 19 | private static Socket clientSocket; |
| 20 | private static BufferedReader inFromServer; |
| 21 | |
| 22 | /** |
| 23 | * Creates client socket makes request to the server. |
| 24 | * |
| 25 | * @throws Exception |
| 26 | */ |
| 27 | private static void start(String host, int port) throws Exception { |
| 28 | if (clientSocket == null) { |
| 29 | clientSocket = new Socket(host, port); |
| 30 | } |
| 31 | if (System.in.available() > 0) { |
| 32 | upload(); |
| 33 | } else { |
| 34 | download(); |
| 35 | } |
| 36 | clientSocket.close(); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * In download mode, client reads data from the socket and writes it to standard output. |
| 41 | * |
| 42 | * @throws Exception |
| 43 | */ |
| 44 | private static void download() throws Exception { |
| 45 | if (inFromServer == null) { |
| 46 | inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); |
| 47 | } |
| 48 | String line; |
| 49 | while ((line = inFromServer.readLine()) != null) { |
| 50 | System.out.println(line); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * In upload mode, client reads data from its standard input device and writes it to the socket. |
| 56 | * |
| 57 | * @throws Exception |
| 58 | */ |
| 59 | @SuppressWarnings("Duplicates") |
| 60 | private static void upload() throws Exception { |
| 61 | DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); |
| 62 | outToServer.writeBytes(new Scanner(System.in).useDelimiter("\\Z").next()); |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Starts execution of the program, requiring a host name and port number as an argument. |
| 67 | * |
| 68 | * @param args |
| 69 | * @throws Exception |
| 70 | */ |
| 71 | public static void main(String[] args) throws Exception { |
| 72 | if (args[0] != null && args[1] != null) { |
| 73 | start(args[0], Integer.parseInt(args[1])); |
nothing calls this directly
no outgoing calls
no test coverage detected