服务器无法从客户端套接字流中读取对象,为什么?

时间:2011-12-24 16:43:50

标签: java sockets networking

我有一个服务器在循环中等待客户端连接。一旦客户端连接,就会创建一个新线程来处理该客户端请求。服务器和客户端很容易相互连接,但我对该线程的问题是它似乎没有读取客户端发送到管道的对象。我到处检查过,但似乎无法找到问题所在。

服务器代码:

public class Server 
{
    private ServerSocket server;

    public Server(int port) throws IOException
    {
        //Port 9367
        this.server = new ServerSocket(port);
        this.server.setReuseAddress(true);
    }

    public void start() throws IOException
    {
        System.out.println("Waiting for client...");
        while(true)
        {
            new Thread(new ClientRequestManager(server.accept())).start();
            System.out.println("client found !");
        }
    }
}

ClientRequestManager代码:

public void run() 
{
    try {
        ObjectInputStream objectInput = new ObjectInputStream(clientSocket.getInputStream());

        System.out.println("Waiting for request...");
        while(true)
        {
            DataRequest request = (DataRequest)objectInput.readObject();

            if(request instanceof TestDataRequest)
            {
                new Thread(new TestEntityManager((TestDataRequest)request, this.clientSocket)).start();
                System.out.println("Client dispatched to the test entity manager !");
            }
            System.out.println("Can't find the right entity manager !");          
        }
    } catch (Exception e) { }   
}

服务器似乎陷入困境:DataRequest request =(DataRequest)objectInput.readObject();

这是我为客户端测试服务器而编写的基本代码:

        //TestDataRequest inherit DataRequest
    TestDataRequest request = new TestDataRequest();
    request.setID(30);
    request.setDescription("test");

    Socket serverSocket = new Socket("localhost",9367);

    ObjectOutputStream clientOutputStream = new ObjectOutputStream(serverSocket.getOutputStream());

    System.out.println("Sending data...");
    clientOutputStream.writeObject(request);
    clientOutputStream.flush();
    System.out.println("Data send !");

我没有得到任何错误,该线程只是阻止。我认为它正在等待将对象写入管道,就像它应该的那样,但是当客户端将对象写入管道时它仍然会阻塞。我不明白为什么。该对象实现了可序列化的...服务器和客户端似乎相互连接并写入/读取到同一个管道......

服务器:addr = / 127.0.0.1,port = 49654,localport = 9367

客户端:addr = localhost / 127.0.0.1,port = 9367,localport = 49654

有人可以向我解释我做错了吗?

0 个答案:

没有答案