[英]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" 为了执行该软件,我将给出路径c:\\ TCPClient.jar /“ Alarm created”
What i want to do is pass the argument from the cmd line argument to the socket. 我想做的是将参数从cmd line参数传递给套接字。 so C:\\TCPClient.jar /"send this string" would pass the argument to the output stream and send it to the socket.
因此C:\\ TCPClient.jar /“发送此字符串”会将参数传递给输出流,并将其发送到套接字。
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. 如果您在命令行中使用参数启动程序,例如
c:\\TCPClient.jar "Alarm created"
,则参数将通过main( String[] args
)参数传递给您的Java程序。
You can write it to the DataOutputStream as 您可以将其写入DataOutputStream中,如下所示:
if (args.length > 0) {
os.writeBytes(args[0]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.