最近我在开发一个小程序,旨在远程关闭浏览器。基本流程如下:
服务器端:
- 创建一个SocketServer以监听特定的端口。
- 接受连接并创建相应的socket对象。
- 从创建的socket读取输入流(此操作被阻塞)。
客户端:
- 创建一个socket对象与服务器建立连接。
- 通过向输出流写入字节向服务器发送关闭浏览器的命令。
- 通过使用socket的输入流上的read()方法读取服务器的反馈(此操作被阻塞)。
代码如下:
Server.java
package socket;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
private static ExecutorService es = Executors.newFixedThreadPool(5);
public static void main(String[] args) throws IOException {
InetAddress targetAddress = null;
NetworkInterface ni = NetworkInterface.getByName("eth2");
System.out.println(ni);
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if(inetAddress.toString().startsWith("/10")) {
targetAddress = inetAddress;
break;
}
}
ServerSocket sSocket = new ServerSocket(11111, 0, targetAddress);
while(true) {
System.out.println("Server is running...");
Socket client = sSocket.accept();
System.out.println("Client at: " + client.getRemoteSocketAddress());
es.execute(new ClientRequest(client));
}
}
}
ClientRequest.java
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ClientRequest implements Runnable {
private Socket client;
public ClientRequest(Socket client) {
this.client = client;
}
@Override
public void run() {
try {
System.out.println("Handled by: " + Thread.currentThread().getName());
// get input/output streams for client socket
InputStream cis = client.getInputStream();
OutputStream cos = client.getOutputStream();
// buffer size : 1024 ?
byte[] buffer = new byte[1024];
int recvSize;
int totalRecvSize = 0;
while(-1 != (recvSize = cis.read(buffer, totalRecvSize, 1024 - totalRecvSize))) {
totalRecvSize += recvSize;
}
String command = new String(buffer, "utf-8");
System.out.println("Command from client: " + command);
String commandNative = CommandMap.getNativeCommand(command.trim());
if(null != commandNative) {
Process np = Runtime.getRuntime().exec(commandNative);
InputStream is = np.getInputStream();
byte[] bufferProcess = new byte[1024];
int bytesRead;
int totalBytesRead = 0;
while(-1 != (bytesRead = is.read(bufferProcess, totalBytesRead, 1024 - totalBytesRead))) {
totalBytesRead += bytesRead;
}
// give feed back of process output
cos.write(bufferProcess);
// close process input stream
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != client) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
最后是 Client.java。
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
public class Client {
private static final int BUF_SIZE = 1024;
// feedback message size will not exceed 1024 bytes
private static final byte[] BUFFER = new byte[BUF_SIZE];
public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
Socket socket = new Socket("10.117.37.176", 11111);
System.out.println("Connected to Server...");
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
String command = "kill ie";
byte[] commandBytes = command.getBytes(Charset.forName("utf-8"));
System.out.println("Send: " + command);
os.write(commandBytes);
System.out.println("After send: " + command);
int totalRecv = 0;
int recvSize;
while(-1 != (recvSize = is.read(BUFFER, totalRecv, BUF_SIZE - totalRecv))) {
totalRecv += recvSize;
}
String feedback = new String(BUFFER, "utf-8");
System.out.println("Feedback: " + feedback);
socket.close();
}
}
再次强调问题:
- 服务器端无法通过调用套接字InputStream对象上的read(buffer, offset, len)来读取命令。它会被阻塞。
- 客户端无法通过调用其套接字InputStream对象上的read(buffer, offset, len)来读取反馈。它会被阻塞。
- 但是,当我在Client.java中注释掉反馈读取操作时,服务器和客户端都可以正常工作。
我想知道这段代码中隐藏的原因是什么?