Android客户端不显示UWP Tcp服务器发送的消息

时间:2016-02-03 17:05:45

标签: c# android tcp uwp

我有一台异步TCP服务器,用于在我的电脑上运行的UWP和Android TCP客户端。 服务器接收客户端消息,但只有在我关闭服务器应用程序时它才会将该行发送回客户端。我已经使用另一个TCP服务器(我使用了TcpListener对象)使用Android客户端,并且它已正常工作。

如果服务器收到消息,我怎样才能将线路发回客户端?

这是TCP服务器:

        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();
        }

这是TCP客户端:

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);
        }

    }

}

1 个答案:

答案 0 :(得分:0)

现在发生了什么:您的客户发送了一行。 服务器读取该行。 服务器发回一行。 客户端不会尝试读取一行,而是连续读取输入流。

您应该让客户端读取一行。使用&#39; readLine()&#39;。

什么是UWP?