有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Runnable类使用Java服务器解析URL

如何使用这样的系统解析URL查询

例如,在变量中获取这些URL参数

http://localhost?format=json&apikey=838439873473kjdhfkhdf

http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html

这些文件是我做的

worker无法命名。java

package 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();
    }
  }
 }

多线程服务器。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);
    }
}

}

调度。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();

}

}

共 (3) 个答案

  1. # 1 楼答案

    到目前为止你做得很好

    每次读取一行InputStream中的数据(BufferedReader可能会有所帮助)。 阅读并学习HTTP协议(请参阅此处的请求消息部分:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

    客户端发送的第一行将遵循以下格式:GET /foo.html?x=y&a=b HTTP/1.1,然后是\n\n方法、URL(带查询参数)和协议。把那条线分开(在空格上)然后根据规格将URL拆分

    在String类中可以找到解析数据所需的一切

  2. # 2 楼答案

    你忘记阅读客户发送的内容了。在http中,客户端打开连接,然后发送请求并等待服务器回复

    要阅读请求,您有两个选项。使用BufferedReader或逐字节读取。 BufferedReader更简单。每一行都有一个字符串,可以轻松拆分或替换字符,或者其他任何形式;)

    读取每个字节的速度稍微快一点,但只有在每秒需要处理大量请求时,它才有意义。而这真的能带来不同。我只是把这些信息告诉你;)

    我已经在你的作品中加入了阅读的必要部分。JAVA 这将读取并打印整个客户端请求

    启动服务器,打开浏览器并键入:http://127.0.0.1:9000/hello?one=1&two=2&three=3 控制台上的第一行将显示:GET/hello?1=1&;2=2&;三=3 HTTP/1.1

    在关闭OutputStream之前,请确保调用flush()方法。这将强制写入所有缓冲字节。如果不这样做,可能会丢失一些字节/字符,并且可能会花费很长时间来查找错误

    try {
        InputStream input  = clientSocket.getInputStream();
    
        // Reading line by line with a BufferedReader
        java.io.BufferedReader in = new java.io.BufferedReader(
            new java.io.InputStreamReader(input));
        String line;
        while ( !(line=in.readLine()).equals("") ){
            System.out.println(line);
        }
    
        OutputStream output = clientSocket.getOutputStream();
        long time = System.currentTimeMillis();
        output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " +
                this.serverText + " - " +
                time +
                "").getBytes());
        output.flush();
        //Flushes this output stream and forces any buffered output bytes to be written out.
        output.close();
        input.close();
        System.out.println("Request processed: " + time);
    

    我不知道你到底在那里干什么。你刚刚告诉我们你需要解析URL,但也许更好的方法是使用simpleframework(http://www.simpleframework.org) 它就像一个嵌入式HTTP服务器,你可以看看教程。它将为您提供一个请求对象,从那里您可以轻松获取url中的参数