簡體   English   中英

Android TCP 服務器消息到桌面 C# 客戶端

[英]Android TCP Server Message to Desktop C# Client

我正在使用 Android 應用程序構建 SMS 發送器應用程序。 Android 應用程序作為服務器工作,而桌面應用程序作為客戶端工作。 我已成功連接兩者。 服務器正在接收來自客戶端的消息。 現在我希望服務器(即 Android 應用程序)將一些基本設備信息發送回客戶端(即桌面應用程序),但不知道如何執行此操作。我的 Android 應用程序代碼在這里。

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

終於找到了解決方案:

第一個定義的包裝 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;
        }


    }

然后等待同步數據

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

然后接收和轉換數據

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM