chatpanel.java

来自「jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,」· Java 代码 · 共 1,285 行 · 第 1/3 页

JAVA
1,285
字号

    protected void setUser(Destination user) {
        this.user = user;
        settingsPanel.userField.setText(user.name);
        if (user.name.length() > 0) {
            settingsPanel.doneButton.setEnabled(true);
        } else {
            settingsPanel.doneButton.setEnabled(false);
        }

        addBuddy(user);
    }

    public String getRelay() {
        return settingsPanel.relayField.getText();
    }

    protected void setRelay(String relay) {
        settingsPanel.relayField.setText(relay);
    }

    public String getPeerId() {
        if (peerId == null) {
            return "";
        } else {
            return peerId;
        }
    }

    protected void setPeerId(String peerId) {
        this.peerId = peerId;

        if (peerId.length() >= UUID_END_INDEX) {
            user.id = ID_PREFIX + NET_GROUP_ID + 
                      peerId.substring(UUID_START_INDEX, 
                                       UUID_END_INDEX) + 
                      PIPE_ID_SUFFIX;

            if (DEBUG) {
                System.out.println("user.id = " + user.id);
            }
        }
    }

    public void run() {

        String peerId = getPeerId();
        byte[] state = null;
        if (peerId != null) {
            state = peerId.getBytes();
        }

        try {
            // connect to the relay
            state = peer.connect(getRelay(), state);
        } catch (Exception e) {
            disconnect();
            if (WARN) {
                System.err.println("status: could not connect");
            }
            return ;
        }

        setPeerId(new String(state));

        if (DEBUG) System.out.println("status: connected");

        try {
            // start listening on user pipe
            peer.listen(CHAT_USERNAME_PREFIX+user.name, user.id, user.type);
        } catch (Exception e) {
            if (DEBUG) System.out.println("status: could not listen to user pipe");
        }

        if (getParent() != null) {
            getParent().validate();
        }

        while (peer != null) {
            Message m = null;
            try {
                m = peer.poll(1000);
            } catch(IOException e) {
                if (WARN) {
                    System.err.println("IOException in PeerNetwork.poll");
                }
            }

            if (m == null) {
                if (DEBUG) {
                    System.out.println("sleep for 10 seconds");
                }
                try {
                    Thread.sleep(10000);
                } catch(InterruptedException e) {
                    if (WARN) {
                        System.err.println("InterruptedException in polling thread");
                    }
                }
            } else {
                if (DEBUG) {
                    System.out.println("handle message");
                }

                handleMessage(m);
            }
        }

        thread = null;
    }

    private String picShareKey = null;
    private Object[] picShareDataBlocks = null;

    private void handleMessage(Message m) {
        String sender = null;
        String message = null;

        String pipeName = null;
        String pipeId = null;
        String pipeType = null;

        String fileKey = null;
        String fileName = null;
        int totalBlocks = 0;
        int blockSize = 0;
        int blockNum = 0;
        int fileSize = 0;
        byte[] dataBlock = null;

        for (int i = 0; i < m.getElementCount(); i++) {
            Element element = m.getElement(i);
            String fullName = element.getNameSpace() + ":" + element.getName();
            if (DEBUG) {
                if (element.getData().length < 100) {
                    String dataStr = new String(element.getData());
                    System.out.println("["+i+"] "+ fullName + " = " + dataStr);
                }
            }

            if (":JxtaTalkSenderName".equals(fullName)) {
                sender = new String(element.getData());;
            } else if (":JxtaTalkSenderMessage".equals(fullName)) {
                message = new String(element.getData());;
            } else if ("proxy:name".equals(fullName)) {
                String dataStr = new String(element.getData());
                if (dataStr.startsWith(CHAT_USERNAME_PREFIX)) {
                    pipeName = dataStr.substring(CHAT_USERNAME_PREFIX.length());
                } else {
                    pipeName = new String(element.getData());;
                }
            } else if ("proxy:id".equals(fullName)) {
                pipeId = new String(element.getData());;
            } else if ("proxy:arg".equals(fullName)) {
                pipeType = new String(element.getData());;

            // PicShare block
            } else if (":TotalBlocks".equals(fullName)) {
                try {
                    totalBlocks = Integer.parseInt(new String(element.getData()));
                } catch (NumberFormatException e) {
                }
            } else if (":BlockSize".equals(fullName)) {
                try {
                    blockSize = Integer.parseInt(new String(element.getData()));
                } catch (NumberFormatException e) {
                }
            } else if (":BlockNum".equals(fullName)) {
                try {
                    blockNum = Integer.parseInt(new String(element.getData()));
                } catch (NumberFormatException e) {
                }
            } else if (":FileSize".equals(fullName)) {
                try {
                    fileSize = Integer.parseInt(new String(element.getData()));
                } catch (NumberFormatException e) {
                }
            } else if (":FileName".equals(fullName)) {
                fileName = new String(element.getData());
            } else if (":FileKey".equals(fullName)) {
                fileKey = new String(element.getData());
            } else if (":DataBlock".equals(fullName)) {
                dataBlock = element.getData();
            }
        }

        if (sender != null && message != null) {
            log(sender + "> " + message);
        } else if (pipeName != null && pipeId != null && pipeType != null) {
            Destination newBuddy = new Destination(pipeName, pipeId, pipeType, "");
            if (! resultList.contains(newBuddy)) {
                buddyAddPanel.resultList.add(newBuddy.name);
                resultList.addElement(newBuddy);
            }
        } else if (fileKey != null) {

            // Is start of a new Image?
            if (! fileKey.equals(picShareKey) || picShareDataBlocks == null) {
                picShareKey = fileKey;
                picShareDataBlocks = new Object[totalBlocks];
            }

            // save this block of data
            if (blockNum < picShareDataBlocks.length) {
                picShareDataBlocks[blockNum] = dataBlock;
            }

            if (picShareDataBlocks.length == 1) {
                // single block image
                imagePanel.setImage(dataBlock, fileName);
                log("[ image: " + fileName + " ]");

                if (isMessengerPanel) {
                    selectPanel(imagePanel, "Picshare with " + currentBuddy.name);
                }

            } else {
                // check to see if we have all of the blocks
                int i = 0;
                for (; i < picShareDataBlocks.length && picShareDataBlocks[i] != null; i++) {
                }

                if (i == picShareDataBlocks.length) {
                    // all of the blocks are available, copy into one block
                    byte[] bigBlock = new byte[fileSize];
                    int idx = 0;

                    for (i = 0; i < picShareDataBlocks.length; i++) {
                        byte[] block = (byte[])picShareDataBlocks[i];
                        for (int j = 0; j < block.length; j++) {
                            bigBlock[idx++] = block[j];
                        }
                    }

                    imagePanel.setImage(bigBlock, fileName);
                    log("[ image: " + fileName + " ]");

                    if (isMessengerPanel) {
                        selectPanel(imagePanel, "Picshare with " + currentBuddy.name);
                    }

                }
            }
        }

    }

    private synchronized void connect() {

        if (peer != null) {
            peer = null;
        }

        if (thread != null) {
            if (DEBUG) {
                System.out.println("status: already connected, disconnecting");
            }
            thread.interrupt();
            try {
                thread.join();
            } catch (Exception e) {
                if (WARN) {
                    System.err.println("status: InterruptedException in join()");
                }
            }
            if (DEBUG) {
                System.out.println("status: disconnected");
            }
        }

        if (DEBUG) {
            System.out.println("status: connecting");
        }

        peer = PeerNetwork.createInstance(user.name);

        // start the polling thread
        thread = new Thread(this);
        thread.start();
    }

    private void cancel() {
        disconnect();
    }

    private synchronized void disconnect() {
        peer = null;

        if (DEBUG) {
            System.out.println("status: disconnected");
        }

        if (thread != null) {
            thread.interrupt();
        }
    }

    private void search() {
        String query = buddyAddPanel.queryField.getText();

        if (query == null || "".equals(query)) {
            query = "*";
        }
        query = CHAT_USERNAME_PREFIX + query;

        try {
            if (DEBUG) {
                System.out.println("start search for " + query);
            }

            buddyAddPanel.resultList.removeAll();
            resultList.removeAllElements();

            peer.search(PeerNetwork.PIPE, query);

            thread.interrupt();
        } catch (Exception e) {
            if (DEBUG) {
                System.out.println("Could not start search");
            }
        }
    }

    private void sendMessage() {
        String message = messengerPanel.inputField.getText();

        // send the message to the buddy
        try {
            send(message);
            if (! PIPE_TYPE_PROPAGATE.equals(currentBuddy.type)) {
                log(currentBuddy.name + "> " + message);
            }
            messengerPanel.inputField.setText("");
        } catch (IOException e) {
            log("COULD NOT SEND MESSAGE");
        }
    }

    private void send(String message) throws IOException {
        Element[] elm = new Element[3];
        elm[0] = new Element("JxtaTalkSenderName", 
                             user.name.getBytes(), null, null);
        elm[1] = new Element("JxtaTalkSenderMessage", 
                             message.getBytes(), null, null);
        elm[2] = new Element("GrpName", 
                             currentBuddy.group.getBytes(), null, null);

        Message m = new Message(elm);

        peer.send(CHAT_USERNAME_PREFIX+currentBuddy.name, 
                  currentBuddy.id, currentBuddy.type, m);

        thread.interrupt();
    }

    private synchronized void log(String message) {
        messengerPanel.logArea.appendText(message + "\n");
    }

    static class Destination {
        String name;
        String id;
        String type;
        String group;

        Destination(String name, String id, String type, String group) {
            if (name == null) {
                this.name = "";
            } else {
                this.name = name;
            }

            if (id == null) {
                this.id = "";
            } else {
                this.id = id;
            }

            if (type == null) {
                this.type = "";
            } else {
                this.type = type;
            }

            if (group == null) {
                this.group = "";
            } else {
                this.group = group;
            }
        }

        void write(DataOutputStream out) throws IOException {
            out.writeUTF(name);
            out.writeUTF(id);
            out.writeUTF(type);
            out.writeUTF(group);
        }

        public boolean equals(Object obj) {
            if (DEBUG) {
                System.out.println("Destination.equals()");
            }

            if (obj instanceof Destination) {
                Destination dest = (Destination)obj;
                if (name.equals(dest.name) && 
                    id.equals(dest.id) && 
                    type.equals(dest.type) && 
                    group.equals(dest.group)) {
                        return true;
                    }
            }

            return false;
        }

        static Destination read(DataInputStream in) throws IOException {
            String name = in.readUTF();
            String id = in.readUTF();
            String type = in.readUTF();
            String group = in.readUTF();

            return new Destination(name, id, type, group);
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?