使用socket将字符串从android发送到C#

时间:2013-05-28 14:12:18

标签: java android sockets simulator

我从android发送一个字符串到C#,从C#发送到android 它适用于模拟器,但不适用于真正的Android设备

  

我的手机使用android 2.3

这是我在Android上的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    hienthi_lv_tab2 = (ListView) findViewById(R.id.lvhienthi);

    chuoi = (EditText) findViewById(R.id.string);
    ipserver = (EditText) findViewById(R.id.ipserver);

    txt = (TextView) findViewById(R.id.Show);

    quit = (Button) findViewById(R.id.quit);
    connect = (Button) findViewById(R.id.Connect);
    send = (Button) findViewById(R.id.Send);

    quit.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            finish();
        }
    });

    send.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            OUT_message = chuoi.getText().toString();


            new Thread(new Runnable() {


                final Handler handler = new Handler();

                final Runnable updateUI2 = new Runnable() {

                    public void run() {
                        // TODO Auto-generated method stub
                        OUT_message = "Android: " + OUT_message;
                        add_chuoi(OUT_message);

                    }
                };

                public void run() {
                    // TODO Auto-generated method stub

                    PrintWriter out;
                    try {
                        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
                        out.println(OUT_message);
                        out.flush();

                        handler.post(updateUI2);

                        out.close();


                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();

           Thread C_thread = new Thread(new ClientThread());
            C_thread.start();
}
    });

    connect.setVisibility(1);
    connect.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // TODO Auto-generated method stub
            connect.setVisibility(v.GONE);
            Thread C_thread = new Thread(new ClientThread());
            C_thread.start();
        }
    });

}
        public class ClientThread implements Runnable {

    final Handler handler = new Handler();

    final Runnable updateUI = new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            txt.setText(IN_message);
            IN_message = "Server: " + IN_message;
            add_chuoi(IN_message);
        }
    };

    public void run() {
        // TODO Auto-generated method stub

        try {

            IP = ipserver.getText().toString();
            serverAddr = InetAddress.getByName(IP);
            state_connnect = true;

            Scanner in;

            while (state_connnect) {

                s = new Socket(serverAddr, 4444);

                in = new Scanner(s.getInputStream());
                IN_message = in.nextLine();


                handler.post(updateUI);

                in.close();
                s.close();

            }

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
public void add_chuoi(String chuoi) {
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array_operator);
    array_operator.add(chuoi);
    hienthi_lv_tab2.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}

}

这是我在C#上的代码:

private void Form1_Load(object sender, EventArgs e)
    {
        CheckForIllegalCrossThreadCalls = false;
        String hostname = "";
        System.Net.IPHostEntry ip = new IPHostEntry();
        hostname = System.Net.Dns.GetHostName();
        ip = System.Net.Dns.GetHostByName(hostname);

        lblhostname.Text = "Tên Server : " + ip.HostName;
        foreach (System.Net.IPAddress listip in ip.AddressList)
        {
            lblip.Text ="Địa Chỉ IP Server : "+listip.ToString();

            IPAddress ipAd = IPAddress.Parse(listip.ToString());
            myList = new TcpListener(ipAd, 4444);
            myList.Start();
        }
    }

    void connect()
    {
        txt_show.Text="Waitting for connect from android...";
        while (true)
        {
            server_socket = myList.AcceptSocket();


            byte[] data_rec = new byte[1024];
            int k = server_socket.Receive(data_rec);


                char cc;
                String mes = null;
                for (int i = 0; i < k - 1; i++)
                {
                    cc = Convert.ToChar(data_rec[i]);
                    mes += cc.ToString();
                }
                if (mes != null)
                {
                    string_rec = mes.ToString();
                    txt_show.Text += Environment.NewLine + "Android: " + mes;
                }
        }
    }

    private void btn_send_Click(object sender, EventArgs e)
    {


        String data_send = txt_send.Text;
        ASCIIEncoding asen = new ASCIIEncoding();
        server_socket.Send(asen.GetBytes(data_send));
        txt_show.Text += Environment.NewLine + "Server : " + txt_send.Text;
        txt_send.Text = "";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        S_thread = new Thread(connect);
        S_thread.Start();
    }

这是logcat:

FATAL EXCEPTION:Thread-10 java.util.NoSuchElementException 
at java.util.Scanner.nextLine(Scanner.java:1417) 
at iNET.Android.Thread_TCP.ThreadActivity$ClientThread.run(ThreadActivity.java:207) 
at java.lang.Thread.run(Thread.java:1019) 

谢谢大家!

1 个答案:

答案 0 :(得分:0)

不完全确定,但我的猜测是你在Mobile和Pc中使用不同的专用网络。这就是为什么你可以在使用模拟器时发送数据的原因(因为它们都在电脑上)但不能用移动设备发送。

发表评论后,我认为您的电脑是在私人网络中。所以你不能使用输入的ip从android应用程序发送消息。