このようなシステムでURLクエリを解析するにはどうすればよいですか。URL Runnableクラスを使用したJavaサーバーでの解析
たとえば、これらのURL引数を変数として取得するようなものです。
http://localhost?format=json&apikey=838439873473kjdhfkhdf
http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html
私は
MultiThreadedServer.javapackage servers;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.Socket;
/**
*/
public class WorkerRunnable implements Runnable{
protected Socket clientSocket = null;
protected String serverText = null;
public WorkerRunnable(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
public void run() {
try {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " +
this.serverText + " - " +
time +
"").getBytes());
output.close();
input.close();
System.out.println("Request processed: " + time);
} catch (IOException e) {
//report exception somewhere.
e.printStackTrace();
}
}
}
WorkerRunnable.javaこれらのファイルに
を作りました
package servers; import java.net.ServerSocket; import java.net.Socket; import java.io.IOException; public class MultiThreadedServer implements Runnable{ protected int serverPort = 8080; protected ServerSocket serverSocket = null; protected boolean isStopped = false; protected Thread runningThread= null; public MultiThreadedServer(int port){ this.serverPort = port; } public void run(){ synchronized(this){ this.runningThread = Thread.currentThread(); } openServerSocket(); while(! isStopped()){ Socket clientSocket = null; try { clientSocket = this.serverSocket.accept(); } catch (IOException e) { if(isStopped()) { System.out.println("Server Stopped.") ; return; } throw new RuntimeException( "Error accepting client connection", e); } new Thread( new WorkerRunnable( clientSocket, "Multithreaded Server") ).start(); } System.out.println("Server Stopped.") ; } private synchronized boolean isStopped() { return this.isStopped; } public synchronized void stop(){ this.isStopped = true; try { this.serverSocket.close(); } catch (IOException e) { throw new RuntimeException("Error closing server", e); } } private void openServerSocket() { try { this.serverSocket = new ServerSocket(this.serverPort); } catch (IOException e) { throw new RuntimeException("Cannot open port 8080", e); } } }
Dispatch.java
package servers;
public class Dispatch {
/**
* @param args
*/
public static void main(String[] args) {
MultiThreadedServer server = new MultiThreadedServer(9000);
new Thread(server).start();
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stopping Server");
server.stop();
}
}
私は上記のコードを使用して、学校でプロジェクト用のサーバーを実行しています。私はJavaのネットワークプログラミングに精通していません。私はURLの引数を解析したい。 – BillPull
これは実際の回答ですか?いいえ、それはなぜ「答え」と言うのでしょうか? – Whymarrh
@Whymarrh私は質問自体についてのコメントを介して質問することができないので、質問する以外の選択肢はありません。投票結果ありがとうございました。 –