TCPClient: <pre lang="Java"><pre>package tcpclient; import java.net.*; import java.io.*; public class TCPClient { public TCPClient() {} public byte[] askServer(String hostname, int port, byte[] toServerBytes) throws IOException { Socket clientSocket = new Socket(hostname, port); OutputStream outToServer = clientSocket.getOutputStream(); outToServer.write(toServerBytes); InputStream inFromServer = clientSocket.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] bufferArray = new byte[bufferSize]; int result; int responseLength = 0; try { while (responseLength == inFromServer.read()) { if (responseLength <= bufferSize && responseLength != -1) { result = inFromServer.read(bufferArray, 0, responseLength); baos.flush(); baos.write(result); } else { result = inFromServer.read(bufferArray, 0, bufferSize); baos.flush(); baos.write(result); if (inFromServer.available() == 0) { byte bytesLeft = (byte) inFromServer.read(); if (bytesLeft != -1) { baos.write(bytesLeft); } } } break; } } catch (IOException e) { e.printStackTrace(); } inFromServer.close(); clientSocket.close(); return baos.toByteArray(); } }
import java.net.*; import java.io.*; import tcpclient.TCPClient; public class TCPAsk { /* * Usage: explain how to use the program, then exit with failure status */ private static void usage() { System.err.println("Usage: TCPAsk host port <data to server>"); System.exit(1); } /* * Main program. Parse arguments on command line and call TCPClient */ public static void main( String[] args) { String hostname = null; int port = 0; byte[] userInputBytes = new byte[0]; try { // Get mandatory command line arguments: hostname and port number int argindex = 0; hostname = args[argindex++]; port = Integer.parseInt(args[argindex++]); // Remaining arguments, if any, are string to send to server if (argindex < args.length) { // Collect remaining arguments into a string with single space as separator StringBuilder builder = new StringBuilder(); boolean first = true; while (argindex < args.length) { if (first) first = false; else builder.append(" "); builder.append(args[argindex++]); } builder.append("\n"); userInputBytes = builder.toString().getBytes(); } } catch (ArrayIndexOutOfBoundsException | NumberFormatException ex) { // Exceeded array while parsing command line, or could // not convert port number argument to integer -- tell user // how to use the program usage(); } try { TCPClient tcpClient = new tcpclient.TCPClient(); byte[] serverBytes = tcpClient.askServer(hostname, port, userInputBytes); String serverOutput = new String(serverBytes); System.out.printf("%s:%d says:\n%s", hostname, port, serverOutput); } catch(IOException ex) { System.err.println(ex); System.exit(1); } } }
59645 22-03-07 19:52:59 57 0 0 711.4 UTC(NIST) *
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)