为什么以下代码命中IOException?

时间:2015-08-04 12:20:35

标签: java

客户等级

import java.io.PrintWriter;
import java.net.Socket;

public class Client 
{
    public static void main(String[] args) 
    {
        try 
        {
            System.out.println(" Starting Client ");
            Socket socket = new Socket ("localhost",55555);
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
            printWriter.println("Hello from client");
            printWriter.println("Conected, Yes!");
            socket.close();// Changes as suggested by Jack
        } 
        catch (Exception e) 
        {
            System.out.println(e);
        }


    }
}

服务器类

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

public class Server 
{
    public static void main(String[] args)
    {
        System.out.println(" inside main ");
        try 
        {
            System.out.println("Starting Server");
            ServerSocket serverSocket= new ServerSocket(55555);
            Socket clientSocket = serverSocket.accept();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String inputLine;
            while ((inputLine= bufferedReader.readLine())!=null) 
            System.out.println("Server Message:"+inputLine);

        } 
        catch (IOException e) 
        {
            System.out.println("IOException "+e);
        }
    }
}

Output:
Starting Server
Server Message:Hello from client
Server Message:Conected, Yes!
IOException java.net.SocketException: Connection reset

客户端和服务器java文件位于同一个包中。 什么会在以下代码中触发IOException? 它与Eclipse有关吗?     仅供参考,我正在使用Eclipse SDK     版本:4.2.2     构建ID:M20130204-1200

2 个答案:

答案 0 :(得分:2)

问题是您的客户端打开Socket,发送一些数据然后退出程序,从而突然关闭连接。

您应该从客户端呼叫close()上的Socket,以通知服务器它将关闭的套接字。

答案 1 :(得分:0)

正如@Jack在他的回答中提到的,你需要在客户端应用程序退出之前关闭()套接字。

套接字是AutoCloseable

使用可关闭资源的安全工作方式是在try块中创建:

public class Client {
    public static void main(String[] args) {
            System.out.println(" Starting Client ");
            try(Socket socket = new Socket("localhost", 55555)) {
                PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                printWriter.println("Hello from client");
                printWriter.println("Conected, Yes!");
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

它将在退出时自动关闭(来自试用部分)。