服务器 - 客户端连接问题Java

时间:2015-12-05 21:02:55

标签: java server

我一直在研究这个问题,但似乎无法让它发挥作用。我有一台服务器在发送请求时向客户端发送响应。但是,即使服务器接收并处理请求,服务器似乎也不会发送响应。

服务器类

removeItem()

客户等级

import java.io.*;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import com.sun.net.httpserver.*;

public class Server implements HttpHandler
{

    Server()
    {
    }

    public static void main(String[] args) throws Exception 
    {
        //starts server
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);

        server.createContext("/", new Server());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    public void handle(HttpExchange exchange) throws IOException 
    {
        //request info
        Headers requestHeaders = exchange.getRequestHeaders();

        boolean getItems = requestHeaders.get("RequestType").get(0).equals("getItems");

        //calls the handler method for getItems
        if(getItems)
        {
            try {
                handleGetItemsRequest(exchange);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    //handle a request to get all points
    public void handleGetItemsRequest(HttpExchange exchange) throws IOException, ClassNotFoundException
    {
        System.out.println("Get Items");

        String response = "Here's all of the items";

        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(b);
        o.writeObject(response);
        o.close();
    }

    /*public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(b);
        o.writeObject(obj);
        return b.toByteArray();
    }*/

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream b = new ByteArrayInputStream(bytes);
        ObjectInputStream o = new ObjectInputStream(b);
        return o.readObject();
    }

}

1 个答案:

答案 0 :(得分:0)

问题是在Server类中,handleGetItemRequest创建一个新的outputStream,而不是使用由HttpExchange对象提供的。 请参阅the reference here,您可以使用exchange.getResponseBody()为您提供OutputStream,您可以在创建ObjectOutputStream时将其用作参数。

ObjectOutputStream o = new ObjectOutputStream(exchange.getResponseBody());