简体   繁体   English

如何在Java中制作服务器和客户端?

[英]How to make server and client in java?

I i am making a server/client but there seems to be a problem. 我正在制作服务器/客户端,但似乎有问题。 I cannot seem to connect when i click the button.Please help.Not sure what i did wrong.Feel free to edit code to fix it then comment please.I have a connect button,and a send button. 我单击按钮后似乎无法连接。请帮助。不确定我做错了什么。随时编辑代码进行修复,然后请注释。我有一个连接按钮和一个发送按钮。 I think it has something to do with the highlighted code but it could be anything. 我认为这与突出显示的代码有关,但是可以是任何东西。 I know this isnt very specific but basically heres the code and it doesnt work. 我知道这不是很具体,但基本上是这里的代码,它不起作用。 I cant connect . 我无法连接。 please help! 请帮忙!

Client 客户

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("Disconnected\n");
            sock.close();
        } catch(Exception ex){
            txtChat.append("Failed to disconnect\n");
        }
        isConnected = false;
        txtUser.setEditable(true);
        userList.setText("");
    }

(This is the highlighted part where i think the problem is) (这是我认为问题所在的突出显示的部分)

 ***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 Again\n");
            txtUser.setEditable(true);
        }
        ListenThread();
    } else if (isConnected == true){
        txtChat.append("You is connected bra\n");
    } 
}***               

(Ends here-the problem/highlighted part) (到此结束-问题/突出部分)

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 sent\n");
        }
        txtMsg.setText("");
        txtMsg.requestFocus();

    }

A couple things: 几件事:

  1. You're getting a java.net.ConnectionException (see below) because the connection is being refused. 您正在获得java.net.ConnectionException (请参见下文),因为连接被拒绝。 This could be because the server you are trying to connect to is not running, the server is not accepting client connections, the server is not accessible by the client, or you are connecting to the wrong port number. 这可能是因为您尝试连接的服务器未运行,服务器未接受客户端连接,客户端无法访问该服务器或者您连接的端口号错误。

  2. It is generally bad coding practice to catch Exception directly. 直接捕获Exception通常是不好的编码习惯。 You want to either catch the most specific exception that ranges across the variety of exceptions that can be thrown (in this case, IOException ) or catch each possible one individually, which is the preferred method. 您想要捕获可抛出的各种异常中最具体的异常(在本例中为IOException ),或者分别捕获每个可能的异常,这是首选方法。 Catch the most specific exceptions before the more general ones so that they are not masked by them. 在更一般的例外之前捕获最具体的例外,以免被它们掩盖。 Furthermore it is a good idea to use the Throwable class's getMessage() method so that you can figure out the reason for the exception being thrown. 此外,最好使用Throwable类的getMessage()方法,以便找出引发异常的原因。 For example: 例如:

     } 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 } 

    Of course, the statements in the catch clause can be modified to your liking. 当然, catch子句中的语句可以根据您的喜好进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM