简体   繁体   English

将android客户端连接为C#服务器

[英]Connect android client to be C# server

I developed small client server (client in Android to send data) and server in PC (receive data and print it out), it works only one time (by sending data from android device to pc) the I should close the android app and run it again? 我开发了小型客户端服务器(Android中的客户端发送数据)和PC中的服务器(接收数据并打印出来),它只工作一次(通过从Android设备发送数据到PC)我应该关闭Android应用程序并运行它呢? by the way I have client app in PC it works properly, I can send from it and the server receives but for the client in android! 顺便说一下,我在PC上有客户端应用程序,它可以正常工作,我可以从它发送,服务器收到但是对于Android中的客户端!

here is the android code: 这是android代码:

    public class MainActivity extends Activity {

    private TCPClient mTcpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText editText = (EditText) findViewById(R.id.edit_message);
        Button send = (Button)findViewById(R.id.send_button);        

        // connect to the server
        new connectTask().execute("");

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String message = editText.getText().toString(); 

                //sends the message to the server
                if (mTcpClient != null) {
                    mTcpClient.sendMessage(message);
                }

                editText.setText("");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public class connectTask extends AsyncTask<String,String,TCPClient> {

        @Override
        protected TCPClient doInBackground(String... message) {

            mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
                @Override

                public void messageReceived(String message) {

                    publishProgress(message);
                }
            });
            mTcpClient.run();

            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values); 
        }
    }
  }

and the TCPClient class: 和TCPClient类:

    public class TCPClient {

    private String serverMessage;
    public static final String SERVERIP = "192.168.0.104"; 
    public static final int SERVERPORT = 4444;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    PrintWriter out;
    BufferedReader in;
    DataOutputStream dataOutputStream = null;

    //OutputStream os;

    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    public void sendMessage(String message){
        if (out != null && !out.checkError()) {

            /*
            String toSend = "a";
            byte[] toSendBytes = toSend.getBytes();

            int toSendLen = toSendBytes.length;
            byte[] toSendLenBytes = new byte[4];
            toSendLenBytes[0] = (byte)(toSendLen & 0xff);
            toSendLenBytes[1] = (byte)((toSendLen >> 8) & 0xff);
            toSendLenBytes[2] = (byte)((toSendLen >> 16) & 0xff);
            toSendLenBytes[3] = (byte)((toSendLen >> 24) & 0xff);
            try {
                os.write(toSendLenBytes);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                os.write(toSendBytes);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            */
           out.print(message);            
           out.flush();           


        }
    }

    public void stopClient(){
        mRun = false;
    }

    public void run() {

        mRun = true;

        try {

            InetAddress serverAddr = InetAddress.getByName(SERVERIP);

            Log.e("TCP Client", "C: Connecting...");

            Socket socket = new Socket(serverAddr, SERVERPORT);    

            ///
            //os = socket.getOutputStream();

            if(socket.isBound()){
                Log.i("SOCKET", "Socket: Connected");            
            }
            else{
                Log.e("SOCKET", "Socket: Not Connected");
            }
            try {

                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                /*
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                byte[] bytes = new byte[] {1}; 
                dataOutputStream.write(bytes, 0, bytes.length);
                */
                Log.e("TCP Client", "C: Sent.");                

                Log.e("TCP Client", "C: Done.");

                if(out.checkError())
                {
                    Log.e("PrintWriter", "CheckError");
                }

                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }


                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");


            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {

                socket.close();
            }

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);

        }

    }

    public interface OnMessageReceived {
        public void messageReceived(String message);
    }

}

finally the C# server code: 最后是C#服务器代码:

class Program
{
    static Socket listeningSocket;
    static Socket socket;
    static Thread thrReadRequest;
    static int iPort = 4444;
    static int iConnectionQueue = 100;

    static void Main(string[] args)
    {
        Console.WriteLine(IPAddress.Parse(getLocalIPAddress()).ToString());
        try
        {                
            listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //listeningSocket.Bind(new IPEndPoint(0, iPort));                                
            listeningSocket.Bind(new IPEndPoint(IPAddress.Parse(getLocalIPAddress()), iPort));
            listeningSocket.Listen(iConnectionQueue);

            thrReadRequest = new Thread(new ThreadStart(getRequest));
            thrReadRequest.Start();
        }
        catch (Exception e)
        {
            Console.WriteLine("Winsock error: " + e.ToString());
            //throw;
        }            
    }

    static private void getRequest()
    {
        int i = 0;
        while (true)
        {
            i++;
            Console.WriteLine("Outside Try i = {0}", i.ToString());

            try
            {
                socket = listeningSocket.Accept();

                // Receiving
                //byte[] rcvLenBytes = new byte[4];
                //socket.Receive(rcvLenBytes);
                //int rcvLen = System.BitConverter.ToInt32(rcvLenBytes, 0);
                //byte[] rcvBytes = new byte[rcvLen];
                //socket.Receive(rcvBytes);
                //String formattedBuffer = System.Text.Encoding.ASCII.GetString(rcvBytes);

                byte[] buffer = new byte[socket.SendBufferSize];
                int iBufferLength = socket.Receive(buffer, 0, buffer.Length, 0);
                Console.WriteLine("Received {0}", iBufferLength);
                Array.Resize(ref buffer, iBufferLength);
                string formattedBuffer = Encoding.ASCII.GetString(buffer);

                Console.WriteLine("Data received by Client: {0}", formattedBuffer);

                if (formattedBuffer == "quit")
                {
                    socket.Close();
                    listeningSocket.Close();
                    Environment.Exit(0);
                }

                Console.WriteLine("Inside Try i = {0}", i.ToString());
                Thread.Sleep(500);
            }
            catch (Exception e)
            {
                //socket.Close();
                Console.WriteLine("Receiving error: " + e.ToString());
                Console.ReadKey();
                //throw;
            }

            finally
            {
                socket.Close();
                //listeningsocket.close();
            }
        }
    }

    static private string getLocalIPAddress()
    {
        IPHostEntry host;
        string localIP = "";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
                break;
            }
        }
        return localIP;
    }
}

also here is a link for the code enter link description here 这里还有一个代码链接,在这里输入链接描述

Can I have some help? 我可以帮忙吗?

see this fix . 看到这个修复。 for 对于

out.println(message);            
           out.flush();  

C# read should be C#应该是

  socket = listeningSocket.Accept();
                    using (NetworkStream nt = new NetworkStream(socket))
                    {
                        using (StreamReader reader = new  StreamReader(nt))
                        {
                            string line;
                            string line;

                        //  while ((line = reader.ReadLine()) != null)//as networkstream never got eof. was using it as replacement while(true)                            // {
                          while (true)
                          {
                            try
                            {
                                line = reader.ReadLine();
                            }
                            catch (IOException)
                            {
                                break;
                            }
                            Console.WriteLine(line);
                           }
                        }//using reader
                    }//using ns

There are 3 ways to do : 有3种方法可以做:

    1)using fixed size messages . like we will send only 100 bytes . 
      and we will        receive only 100 bytes

    2)dinamic way . size of message ,then the message itself . 
      like we will send [message.length][message] then on opposite side
      we will receive the size message then read entire message 

    3) using marker . we will send message with end marker 
       (for example \n in our case) 
      we will use stream to read entire message sent to us till reaching that marker . 
      and most stream has readline() that will read till reaching \n

think you wanted to do 2nd way . 认为你想做第二种方式。 i did not look closely to see what was wrong on it . 我没有密切关注它是什么问题。 and plus u commented that one .mainly on this option . 而且你还评论了一个。主要是这个选项。 problems can be with littleendian and bigendian . littleendian和bigendian可能存在问题。

the same code with a little re arrangement is working fine for me. 相同的代码与一点点安排对我来说工作正常。

    try
    {
        socket = listeningSocket.Accept();
        Console.WriteLine("Connectd...");
        while (true)
        {
            try
            {

                // Receiving

                byte[] buffer = new byte[socket.SendBufferSize];
                int iBufferLength = socket.Receive(buffer, 0, buffer.Length, 0);
                Console.WriteLine("Received {0}", iBufferLength);
                Array.Resize(ref buffer, iBufferLength);
                string formattedBuffer = Encoding.ASCII.GetString(buffer);

                Console.WriteLine("Android Says: {0}", formattedBuffer);

                if (formattedBuffer == "quit")
                {
                    socket.Close();
                    listeningSocket.Close();
                    Console.WriteLine("Exiting");
                    Environment.Exit(0);
                }

                //Console.WriteLine("Inside Try i = {0}", i.ToString());
                Thread.Sleep(500);
            }
            catch (Exception e)
            {
                //socket.Close();
                Console.WriteLine("Receiving error: " + e.ToString());
                Console.ReadKey();
                //throw;
            }


        }
    }
    catch (Exception e)
    {
        //socket.Close();
        Console.WriteLine("Error After Loop: " + e.ToString());
    }
    finally
    {
        Console.WriteLine("Closing Socket");
        socket.Close();
        //listeningsocket.close();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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