简体   繁体   中英

Android TCP Server Message to Desktop C# Client

I am building a SMS Sender App with an Android App. Android App is working as server while desktop app working as Client. I have successfully connected both. Server is receiving messages from Client. Now i want Server (ie Android App) to send back some basic device Info to Client (ie Desktop App) but can't figure out how to do this.My Android App code is here.

this.serverThread = new Thread(new ServerThread());
    this.serverThread.start();

class ServerThread implements Runnable {

    public void run() {
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(SERVERPORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {

            try {

                socket = serverSocket.accept();
                CommunicationThread commThread = new CommunicationThread(socket);
                new Thread(commThread).start();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class CommunicationThread implements Runnable {

    private Socket clientSocket;

    private BufferedReader input;

    public CommunicationThread(Socket clientSocket) {

        this.clientSocket = clientSocket;

        try {

            this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));



        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {

        while (!Thread.currentThread().isInterrupted()) {

            try {

                String read = input.readLine();
                updateConversationHandler.post(new updateUIThread(read));


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
class updateUIThread implements Runnable {
    private String msg;

    public updateUIThread(String str) {
        this.msg = str;
    }

    @Override
    public void run() {

        if(msg.equals("I m Connected"))
        {
            vConn.setText("Connected");
            // Send Back Info
        }


        vClientMsg.setText(vClientMsg.getText().toString()+"Client Says: "+ msg + "\n");
    }
}

finally found the solution:

1st Defined a Pack Class

private class Packet
    {
        public Socket CurrentSocket;
        //public byte[] DataBuffer = new byte[4096];
        public byte[] DataBuffer = new byte[1024];

        /// <summary>
        /// Construct a Packet Object
        /// </summary>
        /// <param name="sock">The socket this Packet is being used on.</param>
        /// <param name="client">The client number that this packet is from.</param>
        public Packet(Socket sock)
        {
            CurrentSocket = sock;
        }


    }

then wait for Sync Data

/// <summary>
    /// Start an asynchronous wait for data from the server.  When data is recieved, a callback will be triggered.
    /// </summary>
    private void WaitForData()
    {
        try
        {
            Packet pack = new Packet(_clientSocket);
            _clientSocket.BeginReceive(pack.DataBuffer, 0, pack.DataBuffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), pack);
        }

        catch (SocketException se)
        {
            System.Console.WriteLine("Client EXCEPTION in WaitForData: " + se.Message);
            ToFile(se.Message);
        }
    }

then Receive and Convert Data

/// <summary>
    /// A callback triggered by receiving data from the server.
    /// </summary>
    /// <param name="asyn">The packet object received from the server containing the received message.</param>
    private void OnDataReceived(IAsyncResult asyn)
    {
        try
        {
            Packet socketData = (Packet)asyn.AsyncState;
            int dataSize = socketData.CurrentSocket.EndReceive(asyn);

            if (_receive != null)
            {
                 byte[] bData = new byte[1024];
                bData = socketData.DataBuffer;
                _lastreceivedata = Encoding.ASCII.GetString(bData, 0, dataSize);
                _receive(socketData.DataBuffer, dataSize);

            }


            WaitForData();
        }

        catch (ObjectDisposedException)
        {
            System.Console.WriteLine("Client EXCEPTION in OnDataReceived: Socket has been closed");
        }

        catch (SocketException se)
        {
            System.Console.WriteLine("Client EXCEPTION in OnDataReceived: " + se.Message);

            if (OnDisconnected != null)
                OnDisconnected();

            ToFile(se.Message);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM