Java-使用ObjectInputStream监听套接字 [英] Java - Listening to a socket with ObjectInputStream

查看:102
本文介绍了Java-使用ObjectInputStream监听套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,每次服务器接受连接时,我都会创建一个名为客户端"的线程类,它会创建一个新的客户端....run方法侦听来自客户端的消息,并且我正在使用ObjectInputStream ..

Ok so , i have a thread class called 'Client' every time the server accepts a connection it creates a new Client....The run method listens for messages from the client and i am useing ObjectInputStream ..

   do {            
         ObjectInputStream in = null;

        try {
            in = new ObjectInputStream(socket.getInputStream());
            String message = (String) in.readObject();
            System.out.println(message);
            }
            catch (ClassNotFoundException ex) {
                isConnected = false;
                System.out.println("Progoramming Error");
            }
            catch (IOException ex) {
                isConnected = false;
                System.out.println("Server ShutDown");
                System.exit(0);
            }
    } while(isConnected);

我遇到的问题是,为什么每次循环时我都必须创建一个新的ObjectInputStream ...并且如果我在循环结束时关闭输入流,并且再次循环以获取另一条消息,我将收到错误消息...请帮忙

The Problem i have is that why do i have to create a new ObjectInputStream every time it loops...and if i close the input stream at the end of the loop and it loops again for another message i will get a error...Please some one help

推荐答案

仅一次(在循环外部)为客户端连接创建ObjectInputStream,然后将readObject方法放入循环.

Only create the ObjectInputStream once (outside the loop) for a client connection, then put the readObject method into the loop.

这是一个有效的测试班:

Here's a working test class:

public class TestPrg {

    public static void main(String... args) throws IOException {
        ServerListener server = new ServerListener();
        server.start();

        Socket socketToServer = new Socket("localhost", 15000);
        ObjectOutputStream outStream = new ObjectOutputStream(socketToServer.getOutputStream());

        for (int i=1; i<10; i++) {
            try {
                Thread.sleep((long) (Math.random()*3000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Sending object to server ...");
            outStream.writeObject("test message #"+i);
        }
        System.exit(0);

    }

    static class ServerListener extends Thread {

        private ServerSocket serverSocket;

        ServerListener() throws IOException {
            serverSocket = ServerSocketFactory.getDefault().createServerSocket(15000);
        }

        @Override
        public void run() {
            while (true) {
                try {
                    final Socket socketToClient = serverSocket.accept();
                    ClientHandler clientHandler = new ClientHandler(socketToClient);
                    clientHandler.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class ClientHandler extends Thread{
        private Socket socket;
        ObjectInputStream inputStream;

        ClientHandler(Socket socket) throws IOException {
            this.socket = socket;
            inputStream = new ObjectInputStream(socket.getInputStream());
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Object o = inputStream.readObject();
                    System.out.println("Read object: "+o);
                } catch (IOException e) {
                    e.printStackTrace();

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

在此示例中,字符串通过ObjectStream发送.如果您收到ClassNotFoundException(http://download.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html#readObject()),并且正在使用独立的客户端和服务器程序,则可能需要检查是否客户端和服务器都具有要在其类路径中发送的对象的类.

In this example Strings are sent trough the ObjectStream. If you get the ClassNotFoundException (http://download.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html#readObject()) and are using an independent client and server program than you might check if both the client and the server have the class of the object to send in their class paths.

这篇关于Java-使用ObjectInputStream监听套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆