1

I have looked around and found different ways of doing this, all of which seem to generate an error. Here is what I am trying to run. It's connecting to a server which is already running. Any ideas on how to get this to work or change it so it does work?

String serverAddress = MainActivity.serverAddress;
int port = MainActivity.newport;
Socket socket = new Socket(serverAddress, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);           
String getName=MainActivity.name;

// Process all messages from server, according to the protocol.
while (true) {
    String line = in.readLine();
    if (line.startsWith("SUBMITNAME")) {
        out.println(getName);
    }
    else if (line.startsWith("NAMEACCEPTED")) {
        //textField.setEditable(true);
    }
    else if (line.startsWith("MESSAGE")) {
        mt.append(line.substring(8) + "\n");
    }
}
takendarkk
  • 3,347
  • 8
  • 25
  • 37
Neurotica
  • 11
  • 1
  • Where are you running this code and what are the errors? An `AsyncTask` would be a good idea. Run the network code in `doInBackground()` and update the `UI` on any of the other methods. – codeMagic Jan 18 '14 at 01:20
  • do all network operations using either thread-handler or asynctask – skyshine Jan 18 '14 at 06:33

1 Answers1

0

What is it that aint working? Is it the code itself or do you need help on running this while(true) loop as a thread?

The while(true) loop will hog the main java thread so you wont be able to do any other operations outside of the while-loop. So first I would recommend to make the operations inside of the while-loop to a thread by either implement runnable or create an anonymous class and start the thread.

There are lots of examples on this: Java - creating a new thread

Hope this helps! Message me back if i interpreted your question wrong.

Community
  • 1
  • 1
Philip
  • 2,287
  • 1
  • 22
  • 37