服务器客户端异常

时间:2013-11-20 21:58:35

标签: java

我在运行服务器 - 客户端程序时遇到问题。当我运行我的服务器程序时,它继续运行,永远不会结束。另一方面,当我运行我的客户端程序时,它会抛出异常,如下所示(我的防火墙已关闭)。

回复将不仅仅是赞赏。谢谢

//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

1 个答案:

答案 0 :(得分:0)

服务器永远不会结束,因为您使用了while(true)循环。您的服务器必须通过accept()方法继续侦听新的客户端连接。

关于异常,您的代码在本地和使用远程计算机都可以正常运行。因此,网络配置错误可能是原因,您必须检查服务器/客户端是否可以使用ping命令看到对方。如果是这种情况,请检查服务器是否正在使用netstat收听客户端。