发送数据后,客户端与服务器断开连接

时间:2014-04-13 19:57:46

标签: java sockets network-programming java-io

我正在创建一个客户端 - 服务器远程截图捕获应用程序。我可以成功地在服务器和客户端之间交换屏幕截图。但是一旦捕获并将屏幕截图发送到服务器,客户端就会从服务器断开连接。我希望客户端在捕获屏幕截图后保持连接。我是java输入/输出以及网络编程的新手。任何人都可以指出错误来帮助我吗?

以下是客户端的完整代码。如果还需要服务器代码来解决这个问题,我也会上传我的服务器代码。

客户端

public class ScreenClient {

    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        BufferedImage screen;
        Socket server = new Socket("localhost", 5494);
        BufferedReader bf = new BufferedReader(new InputStreamReader(server.getInputStream()));
        String s;
        s = bf.readLine();

        System.out.println(s);

        if (s.contains("execute")) {
            Rectangle size = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

            screen = robot.createScreenCapture(size);

            int[] rgbData = new int[(int) (size.getWidth() * size.getHeight())];

            screen.getRGB(0, 0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());

            OutputStream baseOut = server.getOutputStream();

            ObjectOutputStream out = new ObjectOutputStream(baseOut);

            out.writeObject(size);

            for (int x = 0; x < rgbData.length; x++) {

                out.writeInt(rgbData[x]);

            }

            out.flush();
        }
    }
}

服务器

public class ScreenServer extends JFrame implements ActionListener {

    String uname;
    BufferedReader br;
    static JTextArea taMessages, taUserList;
    JTextField tfInput;
    static Socket client;//
    JButton btnCapture, btnExit, btnGetUsers;
    static ArrayList<String> users = new ArrayList();
    PrintWriter os;

    public static void main(String[] args) throws Exception {

        Robot robot = new Robot();

        BufferedImage screen;
        ScreenServer screenServer = new ScreenServer();
        screenServer.buildInterface();
        ServerSocket server = new ServerSocket(5494);
        while (true) {



            client = server.accept();
            users.add(client.getInetAddress().getHostName());
            InetAddress inet1 = client.getInetAddress();

            broadcast(inet1.getHostName(), " Has connected!");



            ObjectInputStream in = new ObjectInputStream(client.getInputStream());

            Rectangle size = (Rectangle) in.readObject();

            int[] rgbData = new int[(int) (size.getWidth() * size.getHeight())];

            for (int x = 0; x < rgbData.length; x++) {

                rgbData[x] = in.readInt();

            }





            screen = new BufferedImage((int) size.getWidth(), (int) size.getHeight(), BufferedImage.TYPE_INT_ARGB);

            screen.setRGB(0, 0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());
            InetAddress clientAddress = client.getInetAddress();
            String clientName = clientAddress.getHostName();
            String t = (new Date()).toString();
            ImageIO.write(screen, "png", new File(clientName + ".png"));
        }

    }

    public void buildInterface() {
        btnCapture = new JButton("Capture Screen");
        btnExit = new JButton("Exit");
        btnGetUsers = new JButton("Get Users");



        //chat area
        taMessages = new JTextArea();
        taMessages.setRows(10);
        taMessages.setColumns(50);
        taMessages.setEditable(false);
        //online users list
        taUserList = new JTextArea();
        taUserList.setRows(10);
        taUserList.setColumns(10);
        taUserList.setEditable(false);
        //top panel (chat area and online users list
        JScrollPane chatPanel = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JScrollPane onlineUsersPanel = new JScrollPane(taUserList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JPanel tp = new JPanel(new FlowLayout());
        tp.add(chatPanel);
        tp.add(onlineUsersPanel);
        add(tp, "Center");
        //user input field
        tfInput = new JTextField(50);
        //buttom panel (input field, send and exit)
        JPanel bp = new JPanel(new FlowLayout());
        bp.add(tfInput);
        bp.add(btnCapture);
        bp.add(btnExit);
        bp.add(btnGetUsers);

        add(bp, "South");
        btnCapture.addActionListener(this);
        tfInput.addActionListener(this);//allow user to press Enter key in order to send message
        btnExit.addActionListener(this);
        btnGetUsers.addActionListener(this);

        setSize(500, 300);
        setVisible(true);
        pack();
    }

    @Override
    public void actionPerformed(ActionEvent evt) {

        if (evt.getSource() == btnExit) {
            taMessages.setText(this.client + " has disconnected");
            users.remove(this.client);

            System.exit(0);
        } else if (tfInput.getText().contains("!getusers")) {
            taUserList.setText(" ");
            this.getUsersOnline();

        } else if (evt.getSource() == btnCapture) {
            MessagesThread mt=new MessagesThread(client);
           mt.start();
        }

        if (evt.getSource() == btnGetUsers) {
            taUserList.setText("");
            try {
                // putUserOnline(this.client.getInetAddress().getHostName());
                getUsersOnline();
            } catch (NullPointerException nl) {
                System.out.println("ERROR--> No Client Connection Found");
            }
        }
    }

    private void getUsersOnline() {
        for (String s : users) {
            putUserOnline(s);
        }

    }

    public static void broadcast(String user, String message) {
        // send message to all connected users
        putMessage(user, message);

    }

    public static void putMessage(String uname, String msg) {
        taMessages.append(uname + ": " + msg + "\n");
    }

    public static void putUserOnline(String name) {
        taUserList.setText(name + ": " + "\n");
    }

    public class MessagesThread extends Thread {

        Socket client;

        public MessagesThread(Socket client) {
            this.client = client;
        }

        @Override
        public void run() {
            String ClientName = tfInput.getText();
            try {
                String response = "execute";
                if (users.contains(ClientName)) {

                    os = new PrintWriter(client.getOutputStream(), true);
                    os.println(response);


                }
            } catch (IOException ex) {
                Logger.getLogger(ScreenServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

0 个答案:

没有答案