سؤال

i have this TCP socket (i only posted relevant parts and removed exception throwings):

static Socket clientSocket;
static BufferedReader inFromServer;

The connection part (i call it from another class):

static Socket clientSocket = new Socket(ip, port);
static BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

And to recieve text i have a runnable thread wich i call like this:

public static void StartRecievingText(){
    TCPScanner.setReader(inFromServer);
    Thread t1 = new Thread(new TCPScanner());
    t1.start();
}

The thread:

public class TCPScanner implements Runnable {

static BufferedReader inFromServer;

public static void setReader(BufferedReader reader){
    inFromServer = reader;
}

public void run() {
    while (true) {
            String temp = inFromServer.readLine();
            System.out.println(temp);
        }
    }
}

The thread runs to the inFromServer.readline() part and appears to recieve nothing.

It's my first time working with threads and ...well second time working with tcp connections so i don't know if i've done anything wrong.

Thanks for your help (and sorry for spelling mistakes... still learning english)

هل كانت مفيدة؟

المحلول

Your client is reading lines but you aren't sending lines, so the client blocks forever waiting for a line terminator that never arrives. Either add a newline to what is being sent, or use another read method that doesn't require it.

There are other problems with your code. None of these data items should be static. Your read loop should test the result of readLine() for null, and close the socket and exit if true.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top