java.net.SocketException:Socket在Socket.accept()和Socket.getInputStream()之间关闭

时间:2016-02-28 18:55:22

标签: java sockets network-programming client-server socketexception

我正在尝试创建一个客户端/服务器连接,我对java也是一个新手。所以我得到的错误告诉我套接字已关闭。经过一些工作,我设法编写下面给出的代码。我确实认为将套接字传递给连接类的方式有问题,如果我不得不猜测,导致socket对象可能被关闭?

我已尝试添加等待,以防服务器线程尚未执行,但似乎没有任何影响。也许我应该在自己的命令提示符下使用自己的启动器启动服务器,但是我应该可以正常工作来测试客户端和服务器。

在发送消息之前,我似乎无法找出插座关闭的原因。任何见解将不胜感激!

谢谢!

错误

java.net.SocketException: Socket is closed
    at java.net.Socket.getInputSTream(Unknown Source)
    at Connection.run(Connection.java:17)

Server.java

//main calling snippet. 
import java.lang.Thread;

public class Server {
    public static void main(String[] args) {
        if(args.length != 1) {
            System.err.println("Usage: java Server <port number>");
            System.exit(1);
        }

        int port = Integer.parseInt(args[0]);
        Thread server = new KServer(port);
        server.start();
        //added waits just to make sure the thread was executed? 
        //thinking this might be my problem
        long t = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < t) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        KClient client = new KClient("127.0.0.1",port);
        while (!(client.openConn())) {
            System.out.println("Failed to connect.  Retrying...");
        }
        client.send("Hello World");
        client.closeConn();

    }
}

KServer.java

//the actual server class that manages listening and threading the sockets
import java.net.*;
import java.io.*;

public class KServer extends Thread {

    private int port;
    private ServerSocket sSock;

    public KServer(int thisPort) {
        port = thisPort;
        try {
           sSock = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();            
        }
    }

    public void run() {
        while(true) {
            try (Socket cSock = sSock.accept();) {
                Thread con = new Connection(cSock);
                con.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Connection.java

//Manages sending and receiving messages

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

public class Connection extends Thread {

    Socket socket;

    public Connection(Socket s) {
        socket = s;
    }

    public void run() {     
        String msg;
        BufferedReader in;
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while((msg = in.readLine()) != null) {
                System.out.println(msg);
            }   
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

KClient.java

//manages the clients connection life to the server
import java.net.*;
import java.io.*;

public class KClient {

    private Socket sock;
    private String dest;
    private int port;

    private OutputStreamWriter out;

    public KClient(String dst,int prt) {
        dest = dst;
        port = prt; 
    }

    public boolean openConn() {

        try {
            sock = new Socket(dest,port);
            out = new OutputStreamWriter(sock.getOutputStream(),"ISO-8859-1");          
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }
        return true;
    }

    public void send(String msg) {
        try {
            out.write(msg);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void closeConn() {

        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}

1 个答案:

答案 0 :(得分:2)

不要使用try-with-resources接受套接字。它会关闭接受的套接字,它需要保持打开状态,以便处理线程可以使用它。处理线程负责关闭它。