In my project server socket doesn't respond properly in android. I don't know what's wrong in that? My server side code is stuck in serversocket.accept().
In manifest file i have given internet and foreground service permission. I am beginner and I am trying this for past 3 days and I have spent too much time in that.
This is my server side code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
Socket s;
ServerSocket serverSocket;
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.texview);
button=findViewById(R.id.buttonstart);
connect();
}
public void connect(){
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
button.setEnabled(false);
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
try {
serverSocket=new ServerSocket(8888);
while (true){
s=serverSocket.accept();
DataInputStream datainput=new DataInputStream(s.getInputStream());
String txt=(String)datainput.readUTF();
textView.setText(txt);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
});
}
public void stop(View view) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is client side code for testing in java format
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
try {
Socket s=new Socket("192.168.43.24", 9999);//for bind by ip & port 1
DataOutputStream m=new DataOutputStream(s.getOutputStream());// for send msg
Scanner scan= new Scanner(System.in);
while(true){
System.out.print("Type you msg here :- ");
String send=scan.nextLine();
m.writeUTF(send);
m.flush();
}
} catch (Exception e) {
System.out.println(e);//print error
//TODO: handle exception
}
}
}