完成使用后如何关闭服务器端口?

时间:2014-12-16 07:08:27

标签: java sockets networking server

注意:我在这里发现了类似的问题:

How to close port after using server sockets

但那里没有找到任何满意的答案。

这是我的客户端程序代码:

package hf;

import java.io.*;
import java.net.*;

public class DailyAdviceClient 
{
    private static final int chatPort = 4242;
    public static void main(String[] args)
    {
        DailyAdviceClient client = new DailyAdviceClient();
        client.go();
    }

    private void go()
    {
        try
        {
            Socket socket = new Socket("127.0.0.1",chatPort);
            InputStreamReader inputStream = new InputStreamReader(socket.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(inputStream);

            String advice = bufferedReader.readLine();
            System.out.println("Advice received by the client for today is "+advice);

            bufferedReader.close();
        }
        catch(Exception e)
        {
            System.out.println("Failed to connect to the server");
        }
    }
}

以下是服务器程序的代码:

package hf;

import java.io.*;
import java.net.*;

public class DailyAdviceServer 
{
    private String[] adviceList = {"Take smaller bites",
            "Go for the tight jeans. No they do NOT make you look fat.",
            "One word: inappropriate", 
            "Just for today, be honest. Tell your boss what you *really* think", 
            "You might want to rethink that haircut."};
    private static final int chatPort = 4242;

    public static void main(String[] args)
    {
        DailyAdviceServer server = new DailyAdviceServer();
        server.go();
    }

    private void go()
    {
        try
        {
            ServerSocket serverSocket = new ServerSocket(chatPort);

            while(true)
            {
                Socket socket = serverSocket.accept();

                PrintWriter writer = new PrintWriter(socket.getOutputStream());

                String advice = getTodaysAdvice();

                writer.println(advice);
                writer.close();
            }
        }
        catch(Exception e)
        {
            System.out.println("Error in establishing connection with the client");
        }
    }

    private String getTodaysAdvice()
    {
        String advice = null;

        int randomIndex = (int) (Math.random()*adviceList.length);
        advice = adviceList[randomIndex];
        return advice;
    }
}

在应用程序中,只要客户端程序连接到服务器程序,它就会收到一个包含当天建议的字符串。

当我跑步时

netstat -an

在我的Windows计算机的命令提示符中,如上述链接中的一个答案所示,我收到一条消息,说明端口4242

LISTENING

如何关闭端口并使其可供将来重复使用?

2 个答案:

答案 0 :(得分:1)

要摆脱LISTENING端口,您必须致电serverSocket.close().

答案 1 :(得分:-1)

关闭socket.close()writer后,您必须使用bufferedReader。因此,港口可以免费进行另一次通信。