如何用java制作服务器和客户端



我正在制作一个服务器/客户端,但似乎有问题。当我点击按钮时,我似乎无法连接。请帮忙。不确定我做错了什么。请随意编辑代码进行修复,然后发表评论。我有一个连接按钮和一个发送按钮。我认为这与突出显示的代码有关,但它可以是任何东西。我知道这不是很具体,但基本上就是代码,它不起作用。我无法连接。请帮忙!

客户端

public class chat_client extends javax.swing.JFrame {

    String username;
    Socket sock;
    BufferedReader reader;
    PrintWriter writer;
    ArrayList<String>userList = new ArrayList();
    Boolean isConnected = false;

    public chat_client() {
        initComponents();
        getContentPane().setBackground(Color.white);
        this.setIconImage(new ImageIcon(getClass()
                .getResource("dogeIcon.jpg")).getImage());
        this.setLocationRelativeTo(null);
    }
    public class IncomingReader implements Runnable{
        public void run(){
            String stream;
            String[] data;
            String done = "Done", connect = "Connect", 
                    disconnect = "Disconnect", chat = "Chat";
            try {
                while ((stream = reader.readLine()) != null){}
                    data = stream.split("^");
                    if (data[2].equals(chat)){
                        txtChat.append(data[0] + ":" + data[1] + "n");
                    } else if (data[2].equals(connect)){
                        txtChat.removeAll();
                        userAdd(data[0]);
                    } else if (data[2].equals(disconnect)){
                        userRemove(data[0]);
                    } else if (data[2].equals(done)){
                        userList.setText("");
                        writeUsers();
                    }
            } catch(Exception ex){
            }
        }
    }
    public void ListenThread(){
        Thread IncomingReader = new Thread(new IncomingReader());
        IncomingReader.start();
    }
    public void userAdd(String data){
        userList.add(data);
    }
    public void userRemove(String data){
        txtChat.append(data + " has disconnected n");
    }
    public void writeUsers(){
        String[] tempList = new String[(userList.size())];
        userList.toArray(tempList);
        for (String token:tempList){
            userList.append(token + "n");
        }
    }
    public void sendDisconnect(){
        String bye = (username + "^ ^Disconnected");
        try{
            writer.println(bye);
            writer.flush();
        } catch(Exception e){
            txtChat.append("Could Not Send Disconnect Message n");
        }
    }
    public void Disconnect(){
        try{
            txtChat.append("Disconnectedn");
            sock.close();
        } catch(Exception ex){
            txtChat.append("Failed to disconnectn");
        }
        isConnected = false;
        txtUser.setEditable(true);
        userList.setText("");
    }

(这是我认为问题所在的突出部分)

 ***private void connectActionPerformed(java.awt.event.ActionEvent evt) {  
     if (isConnected == false){
        username = txtUser.getText();
        txtUser.setEditable(false);
        try{
            sock = new Socket("localhost", 1023);
            InputStreamReader streamreader 
                    = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(streamreader);
            writer = new PrintWriter(sock.getOutputStream());
            writer.println(username + "^has connected.^Connect");
            writer.flush();
            isConnected = true;

        } catch(Exception ex){
            txtChat.append("Cannot Connect! Try Againn");
            txtUser.setEditable(true);
        }
        ListenThread();
    } else if (isConnected == true){
        txtChat.append("You is connected bran");
    } 
}***               

(此处结束问题/突出显示部分)

private void btn_SendActionPerformed(java.awt.event.ActionEvent evt) {     
    String nothing = ""; 
    if ((txtMsg.getText()).equals(nothing)){
       txtMsg.setText("");
       txtMsg.requestFocus();
    } else {
        try{
            writer.println(username + "^" + txtMsg.getText() + "^" 
                    + "Chat");
            writer.flush();
        } catch (Exception ex){
            txtChat.append("Message was not sentn");
        }
        txtMsg.setText("");
        txtMsg.requestFocus();
    }

两件事:

  1. 由于连接被拒绝,您将获得java.net.ConnectionException(请参阅下文)。这可能是因为您尝试连接的服务器没有运行,服务器不接受客户端连接,客户端无法访问服务器,或者您连接的端口号错误。

  2. 直接捕获Exception通常是不好的编码实践。您希望捕获可以抛出的各种异常中最特定的异常(在本例中为IOException),或者单独捕获每个可能的异常,这是首选方法。在更一般的异常之前捕获最具体的异常,这样它们就不会被它们掩盖。此外,最好使用Throwable类的getMessage()方法,这样您就可以找出抛出异常的原因。例如:

    } catch (java.net.ConnectException ex) {
        System.err.println("ConnectException: " + ex.getMessage()); // May return "Connection refused", "Connection timed out", "Connection reset", etc.
    } catch (java.rmi.UnknownHostException ex) {
        System.err.println("UnknownHostException: " + ex.getMessage()); // Returns the name of the host you were attempting to connect to
    } catch (...) {
        // code here
    } catch (java.io.IOException ex) {
        System.err.println("IOException: " + ex.getMessage()); // May return a problem with the BufferedReader or InputStreamReader or PrintWriter
    }
    

    当然,catch子句中的语句可以根据您的喜好进行修改。

最新更新