Socket communication between two Android applications

I have a huge problem with my Android app and I would like to ask you for help.

I am currently writing an Android Clietn-Server application using sockets. I found many tutorologists on the Internet, and from them I created the foundations for my project. However, all textbooks are intended only to send one message and all. I need to send more of them, so I tried to change it.

These are the code fragments responsible for the server and client. The rest is not important at this time.

Server:

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); serverStatus = (TextView) findViewById(R.id.server_status); recivedMsg = (TextView)findViewById(R.id.rec_msg); SERVERIP = getLocalIpAddress(); Thread fst = new Thread(new ServerThread()); fst.start(); } public class ServerThread implements Runnable { public void run() { try { if (SERVERIP != null) { handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Listening on IP: " + SERVERIP); } }); serverSocket = new ServerSocket(SERVERPORT); while (true) { // listen for incoming clients Socket client = serverSocket.accept(); handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Connected." + System.getProperty("line.separator")); } }); try { line = null; while (connected) { BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); if((line = in.readLine())!=null) { Log.d("ServerActivity", line); handler.post(new Runnable() { @Override public void run() { if(recivedMsg.equals("CLOSE")) { recivedMsg.append("CLOSE socket"); connected = false; } else { recivedMsg.append("MSG: " + line + System.getProperty("line.separator")); } // do whatever you want to the front end // this is where you can be creative } }); } else { recivedMsg.append("empty" + System.getProperty("line.separator")); } } break; } catch (Exception e) { handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones."); } }); e.printStackTrace(); } } } else { handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Couldn't detect internet connection."); } }); } } catch (Exception e) { handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Error"); } }); e.printStackTrace(); } } } 

Client

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); serverIp = (EditText) findViewById(R.id.server_ip); connectPhones = (Button) findViewById(R.id.connect_phones); sendField = (EditText) findViewById(R.id.send_field); sendMsg = (Button) findViewById(R.id.msg_send); connectPhones.setOnClickListener(connectListener); sendMsg.setOnClickListener(sendMessage); } @Override protected void onStop() { super.onStop(); try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); //send output msg String outMsg = "CLOSE"; out.write(outMsg); out.flush(); // make sure you close the socket upon exiting s.close(); } catch (IOException e) { e.printStackTrace(); } } private OnClickListener connectListener = new OnClickListener() { @Override public void onClick(View v) { serverIpAddress = serverIp.getText().toString(); runTcpConnection(); sendMessageToServer("Msg"); } }; private OnClickListener sendMessage = new OnClickListener() { @Override public void onClick(View v) { sendMessageToServer(sendField.getText().toString()); } }; private void runTcpConnection() { try { s = new Socket(serverIpAddress, SERVERPORT); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); //send output msg String outMsg = "TCP connecting to " + SERVERPORT + System.getProperty("line.separator"); out.write(outMsg); out.flush(); Log.i("TcpClient", "sent: " + outMsg); SystemClock.sleep(10); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }; public void sendMessageToServer(String str) { try { s = new Socket(serverIpAddress, SERVERPORT); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); //send output msg String outMsg = str + System.getProperty("line.separator"); out.write(outMsg); out.flush(); Log.i("TcpClient", "sent: " + outMsg); s.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.d("", "hello222"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.d("", "hello4333"); } } 

Now the devices are connected correctly. In addition, they send the first connection messages (to OnClickListener connectListener ). The problem is that when I try to send another message using sendMessageToServer , this is not possible. These messages are displayed only after the destruction of client activity.

It is very interesting that without SystemClock.sleep(10); The runTcpConnection() listener behaves strangely. Connected only. displays on the server.

Can someone tell me what should I do to send messages normally?

EDIT: This is what I found:

  • If I’m in a connection sending more messages than all null, and after the second connection error, please connect the phones
  • If I am in a connection sending more messages without an s.close string in sendMessageToServer , only one message passes. After that, after that, an error is not displayed.
  • The runTcpConnection message runTcpConnection always displayed (unless there is no SystemClock.sleep (10) in this function)

Hope this helps someone diagnose my mistake.

+4
source share
1 answer

As I see it, you create a new socket whenever the user clicks the send button, right?
I recommend that you run it only once when the user clicks on the connection, and then you use it in the click send event (because it is TCP, you will be disconnected from the server if you create a new instance of the socket)
Therefore, you should remove these lines in sendMessageToServer:

 s = new Socket(serverIpAddress, SERVERPORT); s.close(); 

and this line in runTcpConnection

 s.close(); 

Socket should be closed whenever you do not want to communicate with the server (onstop is an example or when activity changes ...)
You must also create only one instance of BufferedWriter.
I hope for this help.

+2
source

All Articles