Fabio Cielo
Fabio Cielo

Reputation: 11

Android client doesn't show message send by UWP Tcp server

I have an asynchronous TCP server for a UWP running on my pc and an Android TCP client. Server receives client message but it sends the line back to the client only when I close server application. I have triend Android client with an another TCP server (I used a TcpListener object) and it has worked properly.

How can I send the line back to the client as soon as server gets the message?

Here's TCP server:

        private async void StartServer()
        {
            try
            {
                //Create a StreamSocketListener to start listening for TCP connections.
                StreamSocketListener socketListener  = new StreamSocketListener();

                //Hook up an event handler to call when connections are received.
                socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

                //Start listening for incoming TCP connections on the specified port.
                await socketListener.BindServiceNameAsync("9999");

                TxtServer.Text = " SERVER RUNNNING...";
            }
            catch (Exception e)
            {
                TxtError.Text = e.Message;
            }
        }

        private async void SocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            //Read line from the remote client.
            Stream inStream = args.Socket.InputStream.AsStreamForRead();
            StreamReader reader = new StreamReader(inStream);
            request = await reader.ReadLineAsync();

            //Send the line back to the remote client.
            Stream outStream = args.Socket.OutputStream.AsStreamForWrite();
            StreamWriter writer = new StreamWriter(outStream);

            await writer.WriteLineAsync(request); 
            await writer.FlushAsync();
        }

and here's TCP client:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity{

    TextView textResponse;
    EditText editTextAddress, editTextPort;
    Button buttonConnect, buttonClear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextAddress = (EditText)findViewById(R.id.address);
        editTextPort = (EditText)findViewById(R.id.port);
        buttonConnect = (Button)findViewById(R.id.connect);
        buttonClear = (Button)findViewById(R.id.clear);
        textResponse = (TextView)findViewById(R.id.response);

        buttonConnect.setOnClickListener(buttonConnectOnClickListener);

        buttonClear.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                textResponse.setText("");
            }});
    }


    OnClickListener buttonConnectOnClickListener =
            new OnClickListener(){
                String tMsg = "TEST";

                @Override
                public void onClick(View arg0)
                {
                    MyClientTask myClientTask = new MyClientTask(editTextAddress.getText().toString(),Integer.parseInt(editTextPort.getText().toString()), tMsg);
                    myClientTask.execute();
                }};


    public class MyClientTask extends AsyncTask<Void, Void, Void> {

        String dstAddress;
        int dstPort;
        String response = "";
        String msgToServer;

        MyClientTask(String addr, int port, String msgTo)
        {
            dstAddress = addr;
            dstPort = port;
            msgToServer = msgTo + "\n";
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            Socket socket = null;
            DataOutputStream dataOutputStream = null;

            try {
                socket = new Socket(dstAddress, dstPort);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());

                if(msgToServer != null){
                    dataOutputStream.writeBytes(msgToServer);
                }
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
                byte[] buffer = new byte[1024];

                int bytesRead;
                InputStream inputStream = socket.getInputStream();

                while ((bytesRead = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    response += byteArrayOutputStream.toString("UTF-8");
                }

            }
            catch (UnknownHostException e)
            {
                e.printStackTrace();
                response = "UnknownHostException: " + e.toString();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                response = "IOException: " + e.toString();
            }
            finally
            {
                if(socket != null){
                    try
                    {
                        socket.close();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            textResponse.setText(response);
            super.onPostExecute(result);
        }

    }

}

Upvotes: 0

Views: 305

Answers (1)

greenapps
greenapps

Reputation: 11214

What happens now: Your client sends a line. The server reads that line. The server sends a line back. The client does not try to read a line but continuously reads from the input stream.

You should let the client read a line to. Use 'readLine()'.

And what is UWP?

Upvotes: 0

Related Questions