我正在尝试制作一个可以通过本地路由器在Android设备之间传输整数和字符串的LAN服务器。c# 代码适用于 system.net 指令,但会产生错误,指出"修饰符'static'对此项无效"。
我们是白痴吗?
谢谢
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! rn");
}
Console.Write("Enter Text");
String text = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
Console.Write("Data Sent rn");
Console.Write("Press any key to continue...");
Console.Read();
sck.Close();
};
}
}
}
根据 MSDN 关于静态类和静态类成员:
C# 不支持静态局部变量(在方法范围内声明的变量)。
由于委托是指向方法的指针,这意味着您不能在委托中声明静态变量。如果希望套接字是静态的,则必须在类级别声明它。