2

I have a small program where a Server-Client program is getting connected on the same network, but the same program shows a connection time out error in the client program. I have connected the two systems using LAN cable.

Server

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class DateServer {

  public static void main(String[] args) throws IOException {
    ServerSocket listener = new ServerSocket(9090);
    try {
      while (true) {
        Socket socket = listener.accept();
        try {
          PrintWriter out =
            new PrintWriter(socket.getOutputStream(), true);
          out.println(new Date().toString());
        } finally {
          socket.close();
        }
      }
    } finally {
      listener.close();
    }
  }
}

Client

import java.io.BufferedReader;
import java.io.IOException ;
import java.io.InputStreamReader;
import java.net.Socket;

import javax.swing.JOptionPane;

public class DateClient {

  public static void main(String[] args) throws IOException {
    String serverAddress = JOptionPane.showInputDialog(
      "Enter IP Address of a machine that is\n" +
      "running the date service on port 9090:");
    Socket s = new Socket(serverAddress, 9090);
    BufferedReader input =
      new BufferedReader(new InputStreamReader(s.getInputStream()));
    String answer = input.readLine();
    JOptionPane.showMessageDialog(null, answer);
    System.exit(0);
  }
}
Drenmi
  • 8,492
  • 4
  • 42
  • 51
question
  • 392
  • 1
  • 4
  • 15

2 Answers2

0

Since the code runs on the same computer, three possibilities come to my mind:

  1. The problem can be either your firewall/access to port rights or having IP addresses as mentioned by other fellows.
  2. You are setting the IP address of the server wrong.
  3. The IP address of the server does not lie on the subnet mask of your network. If you have literaly connected the two computers with a cable (no routers in the middle) you probably haven't setup a DHCP, i.e., your ip addresses should be manually selected. If the ip is selected randomly, chances are your client computer can't find the server computer. try manually setting the ip addresses of both computers to an invalid address within the same subnet mask range and see if it works.

For example set the following addresses:

client IP: 192.168.1.10 subnetmask: 255.255.255.0

server IP: 192.168.1.11 subnetmask: 255.255.255.0

Shervin
  • 409
  • 7
  • 13
0

Connecting the two systems with a LAN cable is not sufficient. You have to ensure they have distinct IP addresses, are both in the same IP subnet, and/or have appropriate IP routing tables defined. More typically you would connect both via a router.

user207421
  • 305,947
  • 44
  • 307
  • 483