简体   繁体   中英

Simple Java Chat Program Help, Client Timesout when Connecting With Server

I'm creating a very simple Java chat program, using the Java TCP sockets. I'm new to socket programming and Java. I cannot connect with server, because every time the client connects to server it times out. Maybe, it is because I'm typing the wrong IP address——I don't know.

Here is the code for the Server:

       try
       {

            int fport = Integer.valueOf(port.getText());
            ServerSocket server = new ServerSocket(fport);
            Socket socket = server.accept();
            msg.append("\\n Server is listening to port:" + port.getText());
            BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            out.print(msgtxt.getText());
            msg.append("\n\n" + input.readLine());
            msg.append("\n\n" + Nombre.getText() + msgtxt.getText());


       }
       catch (Exception ex)
       {
           msg.setText("\n\n" + "Error:" + ex.getMessage());
       }

Here is the code for the Client:

        try
        {
            int iport = Integer.valueOf(port.getText());
            int i1;
            int i2;
            int i3;
            int i4;
            i1 = Integer.valueOf(ip.getText());
            i2 = Integer.valueOf(ip1.getText());
            i3 = Integer.valueOf(ip2.getText());
            i4 = Integer.valueOf(ip3.getText());
            byte[] b = new byte[] {(byte)i1, (byte)i2, (byte)i3, (byte)i4 };
            InetAddress ipaddr = InetAddress.getByAddress(b);
            Socket sock = new Socket(ipaddr, iport);
            BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
            output.write(m.getText());
            while(!input.ready()){}
            msg.setText("\n\n" + input.readLine());
            msg.setText("\n\n" + m.getText());
            output.close();
            input.close();
        }
        catch (Exception ex)
        {
            msg.setText("\n\n" + "Error: " + ex.getMessage());
        }

verify that you can connect to the server using telnet (on windows you may need to install it as it's not installed by default anymore).

basically, open a connection to your server and see that it works:

telnet host port

if it works, maybe the problem is not in establising the connection but in waiting for a response from the server (add the exception to your question).

one note: you can open a socket without creating the INetAddress as you did, just new Socket(hostname, port).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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