0

I have a problem in running server-client program. When i run my server program , it keeps on running and never ends up. On other side, when i run my client program it throws an exception as shown below (my firewall is off).

The replies will be more than appreciated. Thanks

//Client Code
import java.io.*;
import java.net.*;
public class DailyAdviceClient
{
    public void go()
    {
        try {
            Socket s = new Socket("127.0.0.1", 4242);
            InputStreamReader read = new InputStreamReader(s.getInputStream());
            BufferedReader z = new BufferedReader(read);
            String advice = z.readLine();
            System.out.println("today you should" + advice);
            z.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
        DailyAdviceClient x = new DailyAdviceClient();
        x.go();
    }
}        

 //Server Code

import java.io.*;
import java.net.*;
public class DailyAdvisor
{
    String[] advicelist = { "take your time", "be patient",
            "don't be diplomatic", " life is really short", "try to fix things" };
    public void go()
    {
        try
        {
            ServerSocket s = new ServerSocket(4242);
            while (true)
            {
                Socket m = s.accept();
                PrintWriter writer = new PrintWriter(m.getOutputStream());
                String advice = getAdvice();
                writer.println(advice);
                writer.close();
                writer.flush();
                System.out.println(advice);
            }
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    private String getAdvice()
    {
        int random = (int) (Math.random() * advicelist.length);
        return advicelist[random];
    }
    public static void main(String[] args)
    {
        DailyAdvisor x = new DailyAdvisor();
        x.go();
    }
}

Exception thrown by Client

ljgw
  • 2,751
  • 1
  • 20
  • 39
user2985842
  • 437
  • 9
  • 24

1 Answers1

0

The Server never ends up because you used a while(true) loop. It is necessary for your server to keep listening to new client connections through the accept() method.

About the exception, your code runs fine both locally and using a remote machine. Thus a network configuration error could be the cause and you must check if both server/client could see each other using the ping command. If this is the case, then check if the server is listening to the client using netstat.

abronan
  • 3,309
  • 4
  • 29
  • 38