Hello everyone
I recently worked on a tiny program aimed at closing the browser remotely. Basic procedures: Server side:
- Create a SocketServer to listen on some specific port.
- Accept the connection and create the corresponding socket object
- Read an InputStream from the created socket (operation blocked on this)
Client side:
- Create a socket object to establish a connection to the server.
- Send a command to close the server-side browser by writing bytes to the OutputStream.
- Read the server feedback using read () in the InputStream socket (locked during this operation)
Code below:
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());
and finally 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;
Repeat problems:
- The server side cannot read the command, causing read (buffer, offset, len) on the socket's InputStream object. He is blocking.
- The client side cannot read the feedback, causing it to read (buffer, offset, len) on its socket's InputStream object. He is blocking.
- But when I comment on the feedback reading operations in Client.java, both the server and the client are working correctly.
I am wondering what are the hidden causes in these codes?
Hope someone can help me, thanks a lot!
source share