开发者

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开发者_如何学JAVA 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜