'Threading with simple client/serverTCP connection
I'm having issues with implementing simple TCP client-server connection in Java, android studio. Networking operations can't run on mainUI thread, asynctask is deprecated, so I'm trying to use Threading. I created client socket in MainActivity and then want it to connect to the server:
client= new ClientTCP();
Log.d("MSG", "Trying to start...");
client.startConnection("xxxxxxxxxxx",8888);
It works well. Now I would like to do more operations such as send a message but I can't just create another Thread for it. At the current state, MainActivity doesn't see client socket as initialized becaused of the threading in Connect() function. It's only working in that particular thread. What should I do now to make both the Connect and sendMsg (and possibly other networking functions) work on the same thread so they are all initialized and seen in ActivityMain? Right now, this:
client.sendMessage("Im gonna crash.");
crashes the app.
public class Client
{
private Socket clientSocket;
private PrintWriter out;
public void Connect(String ip, int port)
{
new Thread(new Runnable() {
@Override
public void run() {
try {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
Log.d("MSG", "Started Connection!");
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void sendMessage (String msg){
new Thread(new Runnable() {
@Override
public void run() {
while(clientSocket.isConnected()) {
out.println(msg+"\n");
}
}
}).start();
}
public void stopConnection() {
try {
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
