更改套接字输入流中的html代码并传递给java中的客户端

时间:2014-11-26 11:18:29

标签: java sockets inputstream serversocket outputstream

我想在java中获取一个代理,在socket中获取服务器的响应并更改html代码,然后将客户端作为套接字连接中的响应传递。
现在我的程序可以从客户端获取请求,并且可以从服务器获得响应并将其正确地传递给客户端 但是我无法更改html代码。这是我的代码:

Thread thread = new Thread() {
    public void run() {
        int bytesRead;
        try {
            while ((bytesRead = streamFromClient.read(request)) != -1) {
                streamToServer.write(request, 0, bytesRead);
                streamToServer.flush();
            }
            Logging incomingLog = new Logging("Incoming", tmpClient.toString());
            incomingLog.doLog();
        } catch (IOException e) {
            Logging IOExceptionLog = new Logging("Error", "Proxy cannot read client request - Client: "
                    + tmpClient.toString() + ".\nException : " + e.getMessage() + "\n");
            try {
                IOExceptionLog.doLog();
            } catch (IOException e1) {
                //Ignore me!!!
            }
        }

        // the client closed the connection to us, so close our
        // connection to the server.
        try {
            streamToServer.close();
        } catch (IOException e) {
            Logging log = new Logging("Error", "Proxy could not close connection to server.");
            try {
                log.doLog();
            } catch (IOException e1) {
                //Ignore me!!!
            }
        }
    }
};

thread.start();// Start the client-to-server request thread running;

// Read the server's responses
// and pass them back to the client;
int bytesRead;
InputStream tempStreamFromServer = streamFromServer;

/*ConvertStream convertor = new ConvertStream();
  String htmlCode = convertor.getStringFromInputStream(tempStreamFromServer);*/

try {
    while ((bytesRead = streamFromServer.read(response)) != -1) {
        streamToClient.write(response, 0, bytesRead);
        streamToClient.flush();
    }

    Logging incomingLog = new Logging("OutComing", tmpClient.toString());
    incomingLog.doLog();
} catch (IOException e) {
    Logging IOExceptionLog = new Logging("Error", "Proxy cannot send client response - Client: "
            + tmpClient.toString() + ".\nException : " + e.getMessage() + "\n");
    IOExceptionLog.doLog();
}

// The server closed its connection to us, so we close our
// connection to our client.
streamToClient.close();

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我终于可以找到问题了。

问题在于threads.I在我的程序中有两个线程:

1.Thread A:得到服务器的响应。

2.Thread B:更改html代码并将其传递给客户端。

现在的问题是,当线程A有一个循环从服务器接受响应并将它们传递给线程B,而线程B也有一个等待来自线程A的响应的循环。

现在,当线程B想要更改html代码时,此操作会给线程B带来延迟,线程A不会等待线程B。

我在对线程B传递一个响应并在处理html代码之后从线程B通知线程A时,用等待线程A解决了这个问题。

有关详细信息,请参阅:http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html