Wrote a simple server using sockets. His goal is to receive data from the user and send it back. The client I wrote in Android Studio, receiving and transmitting (communicating with the server) are made into separate Thread threads. Separately, both sending and receiving messages work, but when I want to listen to the server (in an infinite loop) and send data to it, the application crashes. Here is the client code (no imports):
public class MainActivity extends AppCompatActivity { Handler h; public String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); el = (EditText) findViewById(R.id.editText); h = new Handler(); //Handler нужен для вывода ответа сервера на экран t.start(); //Запуск потока прослушивания ответа }
By clicking on the button, this method is called, which starts a send stream in which the message should be sent to the server:
public void sendmsg (View v) { send.start(); }
Here a stream is executed in which the response of the server is heard, it starts immediately when the application is started.
Thread t = new Thread(new Runnable() { public void run() { try { Socket s = new Socket("IP ADRESS", 8000); while(true) { InputStreamReader listen = new InputStreamReader(s.getInputStream()); BufferedReader buff = new BufferedReader(listen); final String message = buff.readLine();
After receiving the message from the server, I assign it to a variable and with the help of Handler I try to display
h.post(new Runnable() { public void run() { Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); } }); } } catch (IOException e) { e.printStackTrace(); } } });
The stream below should become active during the call to the sendmsg method, it is responsible for sending the message to the server, immediately after sending it should become inactive
Thread send = new Thread(new Runnable() { public void run() { try { Socket ssend = new Socket("IP ADRESS", 8000); PrintWriter writer = new PrintWriter(ssend.getOutputStream()); writer.write("Сообщение серверу"); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }); }
According to the technical task, the server must first accept the message "Message to the client", then send it back, the client must accept this message and display it via Toast.makeText, I connect to the server, but after sending the message nothing happens. I think maybe the problem is that I declare a socket variable with the same address in different threads, but I don’t understand how to fix this problem. Help me please.