List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:GenericClient.java
public static void main(String[] args) throws IOException { try {/*from w w w. ja va2 s.c om*/ // Check the number of arguments if (args.length != 2) throw new IllegalArgumentException("Wrong number of args"); // Parse the host and port specifications String host = args[0]; int port = Integer.parseInt(args[1]); // Connect to the specified host and port Socket s = new Socket(host, port); // Set up streams for reading from and writing to the server. // The from_server stream is final for use in the inner class below final Reader from_server = new InputStreamReader(s.getInputStream()); PrintWriter to_server = new PrintWriter(s.getOutputStream()); // Set up streams for reading from and writing to the console // The to_user stream is final for use in the anonymous class below BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in)); // Pass true for auto-flush on println() final PrintWriter to_user = new PrintWriter(System.out, true); // Tell the user that we've connected to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort()); // Create a thread that gets output from the server and displays // it to the user. We use a separate thread for this so that we // can receive asynchronous output Thread t = new Thread() { public void run() { char[] buffer = new char[1024]; int chars_read; try { // Read characters from the server until the // stream closes, and write them to the console while ((chars_read = from_server.read(buffer)) != -1) { to_user.write(buffer, 0, chars_read); to_user.flush(); } } catch (IOException e) { to_user.println(e); } // When the server closes the connection, the loop above // will end. Tell the user what happened, and call // System.exit(), causing the main thread to exit along // with this one. to_user.println("Connection closed by server."); System.exit(0); } }; // Now start the server-to-user thread t.start(); // In parallel, read the user's input and pass it on to the server. String line; while ((line = from_user.readLine()) != null) { to_server.print(line + "\r\n"); to_server.flush(); } // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end // their input, we'll get an EOF, and the loop above will exit. // When this happens, we stop the server-to-user thread and close // the socket. s.close(); to_user.println("Connection closed by client."); System.exit(0); } // If anything goes wrong, print an error message catch (Exception e) { System.err.println(e); System.err.println("Usage: java GenericClient <hostname> <port>"); } }
From source file:ComplexCompany.java
public static void main(String args[]) throws Exception { ServerSocket servSocket;//from www . j a v a 2 s .c o m Socket fromClientSocket; int cTosPortNumber = 1777; String str; ComplexCompany comp; servSocket = new ServerSocket(cTosPortNumber); System.out.println("Waiting for a connection on " + cTosPortNumber); fromClientSocket = servSocket.accept(); ObjectOutputStream oos = new ObjectOutputStream(fromClientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(fromClientSocket.getInputStream()); while ((comp = (ComplexCompany) ois.readObject()) != null) { comp.printCompanyObject(); oos.writeObject("bye bye"); break; } oos.close(); fromClientSocket.close(); }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null;/*from w w w. j a v a 2s .co m*/ BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); }
From source file:com.gomoob.embedded.EmbeddedMongo.java
/** * Main entry of the program.//from ww w . j a va 2 s .co m * * @param args arguments used to customize starting. * * @throws Exception If an error occured while executing the server. */ public static void main(String[] args) throws Exception { // Creates a default execution context, then the configuration of this context can be changed depending on the // command line parameters received. context = new Context(); // Parse the command line parseCommandLine(args); boolean terminated = false; System.out.println("MONGOD_HOST=" + context.getMongoContext().getNet().getServerAddress().getHostName()); System.out.println("MONGOD_PORT=" + context.getMongoContext().getNet().getPort()); System.out.println("SERVER_SOCKET_PORT=" + context.getSocketContext().getServerSocket().getLocalPort()); Socket socket = null; BufferedReader reader = null; Writer writer = null; while (!terminated) { socket = context.getSocketContext().getServerSocket().accept(); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new OutputStreamWriter(new DataOutputStream(socket.getOutputStream())); System.out.println("Waiting for command..."); String commandString = reader.readLine(); System.out.println(commandString); ICommand command = parseCommandString(commandString); IResponse response = command.run(context); writer.write(response.toJSON()); writer.close(); // If the current socket is opened close it if (!socket.isClosed()) { socket.close(); } // If stop is required terminated = response.isTerminationRequired(); } context.getSocketContext().getServerSocket().close(); }
From source file:com.annuletconsulting.homecommand.server.HomeCommand.java
/** * This class will accept commands from a node in each room. For it to react to events on the server * computer, it must be also running as a node. However the server can cause all nodes to react * to an event happening on any node, such as an email or text arriving. A call on a node device * could pause all music devices, for example. * //w w w.j a va 2 s.co m * @param args */ public static void main(String[] args) { try { socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort()); nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir(); } catch (Exception exception) { System.out.println("Error loading from properties file."); exception.printStackTrace(); } try { sharedKey = HomeComandProperties.getInstance().getSharedKey(); if (sharedKey == null) System.out.println("shared_key is null, commands without valid signatures will be processed."); } catch (Exception exception) { System.out.println("shared_key not found in properties file."); exception.printStackTrace(); } try { if (args.length > 0) { String arg0 = args[0]; if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help") || arg0.equals("-?")) { System.out.println( "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options."); System.out.println("\nHome Command Server command line overrride usage:"); System.out.println( "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh System.out.println("\nDefaults:"); System.out.println("server_port: " + socket); System.out.println("java_user_module_directory: " + userModulesPath); System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath); System.out.println("\n2013 | Annulet, LLC"); } socket = Integer.parseInt(arg0); } if (args.length > 1) userModulesPath = args[1]; if (args.length > 2) nonJavaUserModulesPath = args[2]; System.out.println("Config loaded, initializing modules."); modules.add(new HueLightModule()); System.out.println("HueLightModule initialized."); modules.add(new QuestionModule()); System.out.println("QuestionModule initialized."); modules.add(new MathModule()); System.out.println("MathModule initialized."); modules.add(new MusicModule()); System.out.println("MusicModule initialized."); modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule()); System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized."); modules.add(new HelpModule()); System.out.println("HelpModule initialized."); modules.add(new SetUpModule()); System.out.println("SetUpModule initialized."); modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath)); System.out.println("NonJavaUserModuleLoader initialized."); ServerSocket serverSocket = new ServerSocket(socket); System.out.println("Listening..."); while (!end) { Socket socket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); PrintWriter output = new PrintWriter(socket.getOutputStream(), true); int character; StringBuffer inputStrBuffer = new StringBuffer(); while ((character = isr.read()) != 13) { inputStrBuffer.append((char) character); } System.out.println(inputStrBuffer.toString()); String[] cmd; // = inputStrBuffer.toString().split(" "); String result = "YOUR REQUEST WAS NOT VALID JSON"; if (inputStrBuffer.substring(0, 1).equals("{")) { nodeType = extractElement(inputStrBuffer.toString(), "node_type"); if (sharedKey != null) { if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"), extractElement(inputStrBuffer.toString(), "signature"))) { if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded"))) cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command")); else cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } else result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY"; } else { cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } } System.out.println(result); output.print(result); output.print((char) 13); output.close(); isr.close(); socket.close(); } serverSocket.close(); System.out.println("Shutting down."); } catch (Exception exception) { exception.printStackTrace(); } }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { Socket kkSocket = null; PrintWriter out = null;//from w w w.j a v a 2 s . co m BufferedReader in = null; try { kkSocket = new Socket("taranis", 4444); out = new PrintWriter(kkSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer; String fromUser; while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals("Bye.")) break; fromUser = stdIn.readLine(); if (fromUser != null) { System.out.println("Client: " + fromUser); out.println(fromUser); } } out.close(); in.close(); stdIn.close(); kkSocket.close(); }
From source file:com.splout.db.dnode.TCPStreamer.java
/** * This main method can be used for testing the TCP interface directly to a * local DNode. Will ask for protocol input from Stdin and print output to * Stdout//w ww .j ava 2 s .c om */ public static void main(String[] args) throws UnknownHostException, IOException, SerializationException { SploutConfiguration config = SploutConfiguration.get(); Socket clientSocket = new Socket("localhost", config.getInt(DNodeProperties.STREAMING_PORT)); DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); DataOutputStream outToServer = new DataOutputStream( new BufferedOutputStream(clientSocket.getOutputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter tablespace: "); String tablespace = reader.readLine(); System.out.println("Enter version number: "); long versionNumber = Long.parseLong(reader.readLine()); System.out.println("Enter partition: "); int partition = Integer.parseInt(reader.readLine()); System.out.println("Enter query: "); String query = reader.readLine(); outToServer.writeUTF(tablespace); outToServer.writeLong(versionNumber); outToServer.writeInt(partition); outToServer.writeUTF(query); outToServer.flush(); byte[] buffer = new byte[0]; boolean read; do { read = false; int nBytes = inFromServer.readInt(); if (nBytes > 0) { buffer = new byte[nBytes]; int inRead = inFromServer.read(buffer); if (inRead > 0) { Object[] res = ResultSerializer.deserialize(ByteBuffer.wrap(buffer), Object[].class); read = true; System.out.println(Arrays.toString(res)); } } } while (read); clientSocket.close(); }
From source file:Messenger.TorLib.java
public static void main(String[] args) { String req = "-r"; String targetHostname = "tor.eff.org"; String targetDir = "index.html"; int targetPort = 80; if (args.length > 0 && args[0].equals("-h")) { System.out.println("Tinfoil/TorLib - interface for using Tor from Java\n" + "By Joe Foley<foley@mit.edu>\n" + "Usage: java Tinfoil.TorLib <cmd> <args>\n" + "<cmd> can be: -h for help\n" + " -r for resolve\n" + " -w for wget\n" + "For -r, the arg is:\n" + " <hostname> Hostname to DNS resolve\n" + "For -w, the args are:\n" + " <host> <path> <optional port>\n" + " for example, http://tor.eff.org:80/index.html would be\n" + " tor.eff.org index.html 80\n" + " Since this is a demo, the default is the tor website.\n"); System.exit(2);//from w ww.ja v a2s . co m } if (args.length >= 4) targetPort = new Integer(args[2]).intValue(); if (args.length >= 3) targetDir = args[2]; if (args.length >= 2) targetHostname = args[1]; if (args.length >= 1) req = args[0]; if (req.equals("-r")) { System.out.println(TorResolve(targetHostname)); } else if (req.equals("-w")) { try { Socket s = TorSocket(targetHostname, targetPort); DataInputStream is = new DataInputStream(s.getInputStream()); PrintStream out = new java.io.PrintStream(s.getOutputStream()); //Construct an HTTP request out.print("GET /" + targetDir + " HTTP/1.0\r\n"); out.print("Host: " + targetHostname + ":" + targetPort + "\r\n"); out.print("Accept: */*\r\n"); out.print("Connection: Keep-Aliv\r\n"); out.print("Pragma: no-cache\r\n"); out.print("\r\n"); out.flush(); // this is from Java Examples In a Nutshell final InputStreamReader from_server = new InputStreamReader(is); char[] buffer = new char[1024]; int chars_read; // read until stream closes while ((chars_read = from_server.read(buffer)) != -1) { // loop through array of chars // change \n to local platform terminator // this is a nieve implementation for (int j = 0; j < chars_read; j++) { if (buffer[j] == '\n') System.out.println(); else System.out.print(buffer[j]); } System.out.flush(); } s.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try {//from www .j av a2s.c om serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine; KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
From source file:Bounce.java
/** * The main method.//from ww w .j ava2s . c om */ public static void main(String[] args) { if (args.length < 3) { printUsage(); System.exit(1); } int localPort; try { localPort = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Bad local port value: " + args[0]); printUsage(); System.exit(2); return; } String hostname = args[1]; int remotePort; try { remotePort = Integer.parseInt(args[2]); } catch (NumberFormatException e) { System.err.println("Bad remote port value: " + args[2]); printUsage(); System.exit(3); return; } boolean shouldLog = args.length > 3 ? Boolean.valueOf(args[3]).booleanValue() : false; int numConnections = 0; try { ServerSocket ssock = new ServerSocket(localPort); while (true) { Socket incomingSock = ssock.accept(); Socket outgoingSock = new Socket(hostname, remotePort); numConnections++; InputStream incomingIn = incomingSock.getInputStream(); InputStream outgoingIn = outgoingSock.getInputStream(); OutputStream incomingOut = incomingSock.getOutputStream(); OutputStream outgoingOut = outgoingSock.getOutputStream(); if (shouldLog) { String incomingLogName = "in-log-" + incomingSock.getInetAddress().getHostName() + "(" + localPort + ")-" + numConnections + ".dat"; String outgoingLogName = "out-log-" + hostname + "(" + remotePort + ")-" + numConnections + ".dat"; OutputStream incomingLog = new FileOutputStream(incomingLogName); incomingOut = new MultiOutputStream(incomingOut, incomingLog); OutputStream outgoingLog = new FileOutputStream(outgoingLogName); outgoingOut = new MultiOutputStream(outgoingOut, outgoingLog); } PumpThread t1 = new PumpThread(incomingIn, outgoingOut); PumpThread t2 = new PumpThread(outgoingIn, incomingOut); t1.start(); t2.start(); } } catch (IOException e) { e.printStackTrace(); System.exit(3); } }