在Android上创建LAN tcp服务器时出现静态套接字错误(C#)

时间:2016-01-30 16:00:55

标签: c# android sockets tcp server

我正在尝试创建一个可以通过本地路由器在Android设备之间传输整数和字符串的LAN服务器。 c#代码与system.net指令一起使用,但会产生错误,说“修饰符'静态'对此项无效”。

我们是白痴吗?

谢谢

using System;
using Android.Systems;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Net;
using Java.Net;



namespace My_App
{
    [Activity(Label = "My_App", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.bt_client);

            button.Click += delegate {

                static Socket sck;


                sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
                try
                {
                    sck.Connect("127.0.0.1", 1234);
                }
                catch
                {
                    Console.WriteLine("Unable to connect to remote end point! \r\n");
                }
                Console.Write("Enter Text");
                String text = Console.ReadLine();
                byte[] data = Encoding.ASCII.GetBytes(text);

                sck.Send(data);
                Console.Write("Data Sent \r\n");
                Console.Write("Press any key to continue...");
                Console.Read();
                sck.Close();

            };

        }
    }
}

1 个答案:

答案 0 :(得分:0)

根据Static Classes and Static Class Members上的MSDN:

  

C#不支持静态局部变量(在方法范围内声明的变量)。

由于delegate是指向方法的指针,这意味着您无法在委托中声明静态变量。如果您希望套接字是静态的,则必须在类级别声明它。