[英]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.