客户端无法连接到聊天应用程序中的服务器

时间:2016-03-22 20:55:59

标签: java swing

我正在尝试将客户端连接到服务器,但它无法连接到服务器。当客户端启动时,我希望它等待服务器,当服务器启动时,客户端应该与它连接并开始聊天。

客户端:

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client extends JFrame implements Runnable {
    private Thread t;
    private JTextField userText;
    private JTextArea chatwindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message = "";
    //ip address of the server
    private String serverIp;
    private Socket connection;

    //give the ip address of the server to connect
    public Client(String host){
        super("Client");
        serverIp = host;
        userText = new JTextField();
        userText.setEditable(false);
        userText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent event) {
                // TODO Auto-generated method stub
                sendMessage(event.getActionCommand());
                userText.setText("");
            }
        });

        add(userText,BorderLayout.NORTH);
        chatwindow = new JTextArea();
        add(new JScrollPane(chatwindow),BorderLayout.CENTER);
        setSize(500,500);
        setVisible(true);
    }

    //connect to server
    public void run(){
        while(true){
            showMessage("attempting connection ...... ");
            try {
                connection = new Socket("host", 6789);
                if(connection.isConnected())
                    break;
            } catch (IOException e) {
                // TODO Auto-generated catch block

            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block

            }

        }
        showMessage("connected ..... \n "+connection.getInetAddress().getHostName());
    }
    public void startRunning(){


            try{
                //connect to one specific server
                //connectToServer();
                setupStreams();
                whileChatting();
            }catch(EOFException eofException){
                showMessage("Client terminate connection \n");
            }catch(IOException ioException){
                showMessage("error");
            }/*finally{
                closeCrap();
            }*/

    }

    //connect to server
    /*private void connectToServer() throws IOException{
//new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                while(true){
                    showMessage("attempting connection ...... ");
                    //port on the server =6789
                    try {
                        connection = new Socket("host", 6789);
                        Thread.sleep(50);
                    } catch (UnknownHostException e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    }
                    //connection = new Socket(InetAddress.getByName(serverIp),6789);
                    showMessage("connected ..... \n "+connection.getInetAddress().getHostName());
                    }
            }
        };

    }*/

    //setup streams to send and recieve message
    private void setupStreams() throws IOException{
        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();
        input = new ObjectInputStream(connection.getInputStream());
        showMessage("streams are now setup");
    }

    //while chatting with server
    private void whileChatting() throws IOException{
        ableToType(true);
        do{

            try{
                // to read whatever sent as string
                message = (String)input.readObject();
                showMessage("\n "+message);
            }catch(ClassNotFoundException classNotFoundException){
                showMessage("unknow object type");
            }
        }while(!message.equals("Server :  END"));
    }

    // close the streams and sockets 
    private void closeCrap(){
        showMessage("\n closing crap down .....");
        ableToType(false);
        try{

            output.close();
            input.close();
            connection.close();
        }catch(IOException ioException){
            ioException.printStackTrace();
        }
    }

    //send message to server
    private void sendMessage(String message){
        try{
            output.writeObject("Client : "+message);
            output.flush();
            showMessage("\n Client : "+message);
        }catch(IOException ioException){
            chatwindow.append("error \n ");
        }
    }

    //update chat window
    private void showMessage(final String text){
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                chatwindow.append(text);
            }
        });
    }

    //permession to type in textbox
    private void ableToType(final boolean variable){
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                userText.setEditable(variable);
            }
        });
    }
}

服务器:

 import java.io.*;
   import java.net.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;

    public class Server extends JFrame{

    //that's the area you type your message before sent
    private JTextField userText;
    // the area that display tha conversation
    private JTextArea chatWindow;
    //build output streams
    private ObjectOutputStream output;
    //build input stream
    private ObjectInputStream input;
    private ServerSocket server;
    //connection==socket
    private Socket connection;

    public Server(){
        //add title on tha top of tha winddow
        super("Server");
        userText = new JTextField();
        //before you connect you don't allow to type anything in the message box
        userText.setEditable(false);
        userText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent event) {
                // TODO Auto-generated method stub
                // when user write something and hit enter that method is performed
                //to send message
                sendMessage(event.getActionCommand());
                userText.setText("");

            }
        });
        add(userText,BorderLayout.NORTH);
        chatWindow = new JTextArea();
        add(new JScrollPane(chatWindow));
        setSize(500,500);
        setVisible(true);
    }

    //setup and run the server
    public void startRunning(){
        try{
            //port number=6789
            //only a 100 people allow to hold and wait in the port
            server = new ServerSocket(6789,100);
            // this is the code you want to run it over and over again
            while(true){
                try{
                    //connect and have conversation
                    waitForConnection();
                    //setup tha input and output streams
                    setupStreams();
                    //send message back and forth
                    whileChatting();

                    //exception end of connection
                }catch(EOFException eofException){
                    showMessage("error");
                }finally{
                    closeCrap();
                }
            }

        }catch(IOException ioException){
            ioException.printStackTrace();
        }
    }

    //wait for connection,then display connection information
    private void waitForConnection(){
        showMessage("wainting for some one to connect....\n");
        //connection is the socket that server accept it once someone want to connect
        try {
            connection = server.accept();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //return the address and tha ip adress
        showMessage("now connected to "+connection.getInetAddress().getHostName());
    }

    //get stream to send and receive date
    private void setupStreams() throws IOException{
        //create the path way to another computer want to connect to 
        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();
        input = new ObjectInputStream(connection.getInputStream());
        showMessage(" streams are now setup");

    }

    //during the chat conversation
    private void whileChatting() throws IOException{
        String message = "You are now connected";
        sendMessage(message);
        // let the user type and chatting 
        ableToType(true);
        do{
            //have a conversation
            try{
                //read a message and make sure it a string 
                message = (String)input.readObject();
                showMessage("\n"+message);
            }catch(ClassNotFoundException classNotFoundException){
                showMessage("what is that O.o wired ");
            }
        }while(!message.equals("Client : END"));
    }

    //close streams and sockets after you done chatting
    private void closeCrap(){
        showMessage("\n end of cpnnection ...... \n");
        ableToType(false);
        try{
            //close the streams
            output.close();
            input.close();
            //close the socket
            connection.close();
        }catch(IOException ioException){
            ioException.printStackTrace();

        }
    }

    //send a message to client
    private void sendMessage(String message){
        try{
            //send a message throw the output stream "user name"
            output.writeObject("Server :  "+message);

            output.flush();
            showMessage("\n Server : "+message);
        }catch(IOException ioException){
            //put it in the chat area
        chatWindow.append("\n error O.o that message can't be sent");   
        }
    }

    //update chat window
    private void showMessage(final String text){
        //allow to create a thread -update chat window-
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                // add a message to the chat wondow
                chatWindow.append(text);
            }
        });
    }

    // allow client to type
    private void ableToType(final boolean variable){
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                userText.setEditable(variable);
            }
        });

    }
}

cientChat:

     import javax.swing.JFrame;
    public class CientChat {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        //127.0.0.1 means localhost 
        Client testClient = new Client ("127.0.0.1");
        testClient.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        testClient.run();
        testClient.startRunning();
    }

}

ServerChat:

import javax.swing.JFrame;
public class ServerChat {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Server test = new Server();
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        test.startRunning();
    }

}

1 个答案:

答案 0 :(得分:1)

这样:

connection = new Socket("host", 6789);

不是开始连接的正确方法,您应该尝试" localhost" 或ip " 127.0.0.1"

尝试改为:

connection = new Socket("localhost", 6789);