开发者

Client-server application socket problem

开发者 https://www.devze.com 2023-03-04 07:34 出处:网络
I am currently developing a client-server application and I have this problem: I want to create a different class instance depending on what the connected socket sends, but it only creates the first i

I am currently developing a client-server application and I have this problem: I want to create a different class instance depending on what the connected socket sends, but it only creates the first instance then it stucks. Here is some piece of code:

    Socket clientSocket = null;
    ServerSocket server = null;
    String buff = null;
    transfer tr = null;
    colectieClienti clienti = new colectieClienti();

And:

while (true) {
            try {
                clientSocket = server.accept();
                buff = (new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))).readLine();
                if (buff.equals("client")) {
                    (colectieClienti.useri[colectieClienti.nrUseri++] = new clientThread(clientSocket, stmt)).start();
                } else {
                    tr = new transfer(clientSocket);
                    tr.start();
                }
            } catch (IOException ex) {
                System.out.println(ex);
            }
        }

I have to mention that clientThread is a class that extends Thread and communicates with a GUI, and transfer is a class that only send some files from client to server. The logic is something like this: In the GUI the user connects to the server, so it is created a new instance of clientThread and after this, when the user press a button it creates a new socket (on the client side and send a message to the server, something like "I want to create a new instance of transfer class, which is done by the buff) and receive the data. But it only creates the clientThread instance and then it stucks. Can anyone help me?

LE: This is the constructor of clientThread

 public clientThread(Socket socket, Statement 开发者_如何学Pythonstatement) {
        comunicare = socket;
        try {
            oStream = comunicare.getOutputStream();
            is = new BufferedReader(new InputStreamReader(comunicare.getInputStream()));
            os = new PrintStream(oStream);
        } catch (IOException ex) {
            System.out.println(ex);
        }
        this.statement = statement;
    }


This is only a guess, but are you sending a line terminator from the client? BufferedReader.readLine() reads until it gets a \n, \r, or a \r\n, so if the client is not writing that, the server will just wait.


First and foremost: avoid extending the thread class and opt out for implementing a runnable.

But it only creates the clientThread instance and then it stucks. Can anyone help me?

Then show us what you do when you create the clientThread, showing us what you do on the server (alone) is not enough for us to tell you what you're doing wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号