coolpigs  

问题背景:在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获得已经使用的端口

 

转载请写明出处

转发请写明出处

posted on 2012-02-09 13:13  coolpigs  阅读(7190)  评论(0编辑  收藏  举报