問題背景:在win7上安裝了ubuntu的虛擬機,mac的虛擬機,現在需要在win7上直接調用ubuntu或mac系統中的shell腳本,因此使用socket來解決
問題解決方案:在win7上運行socket的客戶端,在ubuntu或mac系統中運行socket服務器
下面貼出我的代碼,並做簡單的解釋
socket客戶端
SocketClient.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
public static final String ANDROIDIP = "192.168.26.131";
public static final String IOSIP = "192.168.26.132";
public static final String SYMBIANIP = "127.0.0.1";
public static final String ANDROIDCMD = "A";
public static final String IOSCMD = "I";
public static final String SYMBIANCMD = "S";
public static final int SOCKETPORT = 8888;
static Socket socket;
BufferedReader in;
PrintWriter out;
public SocketClient(String sendCommand)
{
try{
if(sendCommand.equals(ANDROIDCMD))
{
socket = new Socket(ANDROIDIP,SOCKETPORT);
}
else if(sendCommand.equals(IOSCMD))
{
socket = new Socket(IOSIP,SOCKETPORT);
}
else if(sendCommand.equals(SYMBIANCMD))
{
socket = new Socket(SYMBIANIP,SOCKETPORT);
}
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
out.println(sendCommand);
System.out.println(sendCommand);
}catch(Exception e)
{
return;
}
}
}
CompileClient.java
public class CompileClient {
public static void main(String[] args) {
new SocketClient(SocketClient.ANDROIDCMD);
System.out.println("compile client start");
}
}
socket服務端(以客戶端發送A命令為例)
SocketServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer implements Runnable{
public static final int SERVERPORT = 8888;
public String acceptedCommand= null;
public static final String command = "A";
@Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
return;
}
while (true){
Socket socket = null;
try {
socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
acceptedCommand = in.readLine();
System.out.println(acceptedCommand);
if(acceptedCommand.equals(new String(command)))
{
System.out.println("run android.sh script");
Runtime.getRuntime().exec("/home/whb/android.sh");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
CompileServer.java
public class CompileServer {
public static void main(String[] args) {
Thread socketServerThread = new Thread(new SocketServer());
socketServerThread.start();
System.out.println("compile server start");
}
}
其中ip地址可通過ifconfig獲得
port至少打於1024,可通過netstat獲得已經使用的端口
轉載請寫明出處
轉發請寫明出處