[英]Pass string from a console input to a tcp socket
我有一个可以执行外部应用程序的软件,我正在尝试使用它在中间创建一个与单独系统通信的人。
为了执行该软件,我将给出路径c:\\ TCPClient.jar /“ Alarm created”
我想做的是将参数从cmd line参数传递给套接字。 因此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);
}
}
}
}
如果您在命令行中使用参数启动程序,例如c:\\TCPClient.jar "Alarm created"
,则参数将通过main( String[] args
)参数传递给您的Java程序。
您可以将其写入DataOutputStream中,如下所示:
if (args.length > 0) {
os.writeBytes(args[0]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.