在客户端JAVA中调用socket.close()时,套接字未关闭服务器端 [英] Socket not closing serverside when calling socket.close() in client JAVA

查看:218
本文介绍了在客户端JAVA中调用socket.close()时,套接字未关闭服务器端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中遇到套接字问题。我有一个 ServerSocket 正在用accept()监听并为每个客户端请求生成线程。客户端和服务器之间的通信正常。我正在使用输入流从serverthreads中的客户端读取数据,例如:

I'm having problems with sockets in java. I have a ServerSocket that is listening with accept() and spawns threads for each client-request. Communication between clients and the server works fine. I am using an inputstream to read data from clients in the serverthreads, like:

inputStream = mySocket.getInputStream();
bytes = inputStream.read(buffer);

我的问题是,如果我从客户端调用socket.close(),阻塞没有任何反应调用 bytes = inputStream.read(buffer); ,它继续阻塞。但是如果我从服务器关闭套接字,那么客户端的 inputStream.read(缓冲区); 将返回-1。

My problem is that if I call socket.close() from the clients, nothing happens to the blocking call of bytes = inputStream.read(buffer);, it continues to block. But it works if I close the socket from the server, then the inputStream.read(buffer); of the client returns "-1".

SERVER-MAINTHREAD:

SERVER-MAINTHREAD:

//SERVER MAIN THREAD, SPAWNS CLIENT THREADS
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (listening){

new ServerThread(serverSocket.accept(), monitor).start();
}

SERVER-CLIENTTHREADS:

SERVER-CLIENTTHREADS:

public class ServerThread extends Thread{

public ServerThread(Socket socket, Monitor monitor) {
        this.socket = socket;
        this.monitor = monitor;
    }

    public void run(){
        byte[] buffer = new byte[1024];
        int bytes;
        //Listen
        while(true){
            try {
                InputStream inputStream = socket.getInputStream();
                monitor.doStuffWithOtherThreads(Object myObject);
                bytes = inputStream.read(buffer); //Problem
                if (bytes == -1){
                    System.out.println("breaks");
                    break;
                }

                byte[] readBuf = (byte[]) buffer;
                String readMessage = new String(readBuf, 0, bytes);
                System.out.println(readMessage);
                System.out.println(bytes);


            } catch (IOException e) {
                System.out.println("Connection closed");
                break;
            }
        }
    }

客户:

InetAddress serverAddr = InetAddress.getByName("serverhostname");

socket = new Socket(serverAddr, PORT);

socket.close(); //Close the socket connection from client. Nothing happens in the serverthread


推荐答案

你发布的服务器代码没有检查-1。所以这是问题或者不是真正的代码,在这种情况下你应该发布真正的代码进行评论。

The server code you posted doesn't check for -1. So either that is the problem or that isn't the real code, in which case you should post the real code for comment.

编辑您发布的代码与您所描述的不符。

EDIT The code you have posted does not behave as you have described.

这篇关于在客户端JAVA中调用socket.close()时,套接字未关闭服务器端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆