简体   繁体   中英

Pass string from a console input to a tcp socket

I have a piece of software that can execute an external application and i am trying to use this to create a man in the middle to communicate with a separate system.

To execute the software i was going to give the path c:\\TCPClient.jar /"Alarm created"

What i want to do is pass the argument from the cmd line argument to the socket. so C:\\TCPClient.jar /"send this string" would pass the argument to the output stream and send it to the socket.

import java.io.*;
import java.util.Scanner;
import java.net.*;
public class TCPClient {

public static void main(String[] args) {

    Socket tcpSocket = null;  
    DataOutputStream os = null;


    try {
        tcpSocket = new Socket("10.0.10.1", 445);
        os = new DataOutputStream(tcpSocket.getOutputStream());

    } catch (UnknownHostException e) {
        System.err.println("Hostname not found");
    } catch (IOException e) {
        System.err.println("Couldnt connect Check Listening port");
    }

if (tcpSocket != null && os != null) {
        try {
            String consoleInput;

           Scanner scanIn = new Scanner(System.in);
           consoleInput = scanIn.nextLine();

           scanIn.close();            

    os.writeBytes(consoleInput);    



   os.close();


        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}           
}

If you start a program with an argument on the command line, for example c:\\TCPClient.jar "Alarm created" , then the arguments will be passed to your java program in the main( String[] args ) parameter.

You can write it to the DataOutputStream as

if (args.length > 0) {
    os.writeBytes(args[0]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM