TCP-IP连接Android App到C#Server

时间:2016-12-22 22:23:42

标签: c# android tcp

所以我真正尝试做的是通过Xamarin Android应用程序与PC / Host接口的DMX接口进行通信。 Allready让我的服务器运行,也适用于我先写的控制台客户端。所以现在我使用与以前相同的方式使用TCPClient编写应用程序,然后通过流写入数据。 因为我在模拟器中运行应用程序,我使用IP 10.0.2.2进行连接,但我无法建立连接。应用程序崩溃或我得到超时执行。一直在尝试和研究两天,现在我很绝望,所以我在这里附上我的代码,希望任何人都能帮忙

谢谢,约翰内斯

应用:

public class MainActivity : Activity
{
    public Stream Stream;
    TcpClient Client = null;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
        //adding control elements from Resource.Layout.Main
        Button at = FindViewById<Button>(Resource.Id.at);
        Button enter = FindViewById<Button>(Resource.Id.enter);
        Button thru = FindViewById<Button>(Resource.Id.thru);
        Button all = FindViewById<Button>(Resource.Id.all);
        Button one = FindViewById<Button>(Resource.Id.one);
        Button two = FindViewById<Button>(Resource.Id.two);
        Button three = FindViewById<Button>(Resource.Id.three);
        Button four = FindViewById<Button>(Resource.Id.four);
        Button five = FindViewById<Button>(Resource.Id.five);
        Button six = FindViewById<Button>(Resource.Id.six);
        Button seven = FindViewById<Button>(Resource.Id.seven);
        Button eight = FindViewById<Button>(Resource.Id.eight);
        Button nine = FindViewById<Button>(Resource.Id.nine); 
        Button zero = FindViewById<Button>(Resource.Id.zero);
        Button comma = FindViewById<Button>(Resource.Id.comma);
        Button connect = FindViewById<Button>(Resource.Id.connect);
        Button clear = FindViewById<Button>(Resource.Id.clear);
        at.Click += (o, e) =>
        {
            UpdateCmdLine("@");
        };
        clear.Click += (o, e) =>
        {
            FlushCmdLine();
        };
        enter.Click += (o, e) =>
        {
            TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
            ProcessData(cmdLine.Text);
            FlushCmdLine();
        };
        thru.Click += (o, e) =>
        {
            UpdateCmdLine("/");
        };
        all.Click += (o, e) =>
        {
          UpdateCmdLine("#");
        };
        one.Click += (o, e) =>
        {
            UpdateCmdLine("1");
        };
        two.Click += (o, e) =>
        {
            UpdateCmdLine("2");
        };
        three.Click += (o, e) =>
        {
            UpdateCmdLine("3");
        };
        four.Click += (o, e) =>
        {
            UpdateCmdLine("4");
        };
        five.Click += (o, e) =>
        {
            UpdateCmdLine("5");
        };
        six.Click += (o, e) =>
        {
            UpdateCmdLine("6");
        };
        seven.Click += (o, e) =>
        {
            UpdateCmdLine("7");
        };
        eight.Click += (o, e) =>
        {
            UpdateCmdLine("8");
        };
        nine.Click += (o, e) =>
        {
            UpdateCmdLine("9");
        };
        zero.Click += (o, e) =>
        {
            UpdateCmdLine("0");
        };
        comma.Click += (o, e) =>
        {
            UpdateCmdLine(",");
        };
        connect.Click += (o, e) =>
        {
            try
            {
                TextView ip = FindViewById<TextView>(Resource.Id.ipField);
                TextView port = FindViewById<TextView>(Resource.Id.portField);
                TextView connectionStatus = FindViewById<TextView>(Resource.Id.connectedStatus);
                Client = new TcpClient("10.0.2.2", 4711);
                connectionStatus.Text = "Connected";
            }
            catch (System.Exception)
            {

            }
        };

        //implementing click functions
    }



    public void UpdateCmdLine(string update)
    {
        TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
        cmdLine.Text += update;
    }

    public void FlushCmdLine()
    {
        TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
        cmdLine.Text = "";
    }

    public int[] GetData(string channel, string value)
    {
        int[] data = new int[] {Int32.Parse(channel), Int32.Parse(value)};
        return data;
    }
    public void SendData(int channel, int data)
    {
        if (Client.Connected)
        {
            Stream = Client.GetStream();
            byte[] outgoingBytes = new byte[] {Convert.ToByte(channel),Convert.ToByte(data)};
            Stream.Write(outgoingBytes,0,outgoingBytes.Length);
        }
    }

    public void ProcessData(string cmdLine)
    {
        string[] divideStackedOps = cmdLine.Split(',');
        foreach (string s in divideStackedOps)
        {
            if (s.Contains("/"))
            {
                string[] dividedThru = s.Split('/');
                int channel1 = Int32.Parse(dividedThru[0]);
                string[] dividedAt = dividedThru[1].Split('@');
                int channel2 = Int32.Parse(dividedAt[0]);
                int value = Int32.Parse(dividedAt[1]);
                for (int e = channel2; e >= channel1; e--)
                {
                    SendData(e, value);
                }
            }
            else if (s.Contains("#"))
            {
                string[]dividedAll = s.Split('#');
                int value = Int32.Parse(dividedAll[1]);
                for (int e = 100; e > 0; e--)
                {
                    SendData(e, value);
                }
            }
        }
    }
}

}

服务器

public class DmxInterface
{
    [DllImport("K8062D.dll")]
    public static extern void StartDevice();

    [DllImport("K8062D.dll")]
    public static extern void SetData(int channel, int data);

    [DllImport("K8062D.dll")]
    public static extern void StopDevice();

    [DllImport("K8062D.dll")]
    public static extern void SetChannelCount(int count);
}


class Program
{
    private static TcpListener Listener;
    private static ArrayList Threads = new ArrayList();
    public static Boolean ServerStopped;

    public static void Main()
    {
        DmxInterface.StartDevice();
        DmxInterface.SetChannelCount(10);
        //Initialize Listener, start Listener
        int port = 4711;
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        Listener = new TcpListener(ip, port);
        Listener.Start();
        Console.WriteLine("Creating new listener on: "+ip+":"+port);
        //Initialize MainServerThread, start MainServerThread
        Console.WriteLine("Starting MainThread");
        Thread mainThread = new Thread(Run);
        mainThread.Start();
        Console.WriteLine("Done");
        while (!ServerStopped)
        {
            Console.WriteLine("Write 'stop' to stop Server...");
            String cmd = "";
            cmd = Console.ReadLine();
            if (cmd.ToLower().Equals("stop"))
            {
                Console.WriteLine("stopping server");
                ServerStopped = true;
            }
            else
            {
                Console.WriteLine("unknow command: " + cmd);
            }
        }
        EndThreads(mainThread);
    }

    public static void EndThreads(Thread mainThread)
    {
        //stopping MainThread
        mainThread.Abort();
        Console.WriteLine("MainThread stopped");
        //stopping all Threads
        for (IEnumerator e = Threads.GetEnumerator(); e.MoveNext();)
        {
            //Getting next ServerThread
            Console.WriteLine("Stopping the ServerThreads");
            ServerThread serverThread = (ServerThread)e.Current;
            //Stop it
            serverThread.Stop = true;
            while (serverThread.Running)
            {
                Thread.Sleep(1000);
            }
        }
        //Stopping Listener
        Listener.Stop();
        Console.WriteLine("listener stopped");
        Thread.Sleep(5000);
        Console.Clear();
    }
    //opening a new ServerThread
    public static void Run()
    {
        while (true)
        {
            Console.WriteLine("Listener waiting for connection wish");
            //waiting for incoming connection wish
            TcpClient client = Listener.AcceptTcpClient();
            Threads.Add(new ServerThread(client));
        }
    }
}

class ServerThread
{
    public bool Stop;
    public bool Running;
    private TcpClient client;

    public ServerThread(TcpClient client)
    {
        this.client = client;
        //starting new thread with run() function
        Console.WriteLine("Starting new ServerThread");
        new Thread(new ThreadStart(Run)).Start();
    }
    //threaded function
    public void Run()
    {
        Stream stream = null;
        Boolean gotstream = false;
        Console.WriteLine("Reading incoming Data Stream");
        Running = true;
        while (!gotstream)
        {
            //making sure stream is not null to avoid exeption
            if (client.GetStream() != null)
            {
                //getting stream, setting flag true
                stream = client.GetStream();
                gotstream = true;
            }
        }
        Boolean loop = true;
        byte[] incomingValues = new byte[] {255, 255};
        Boolean gotData = false;
        while (loop)
        {
            //checking if a remote host is still connected
            if (client.Connected)
            {
                try
                {
                    //reading Byte Array
                    stream.Read(incomingValues, 0, incomingValues.Length);
                    gotData = true;
                }
                catch (Exception e)
                {
                    //catching exeptions
                    Console.WriteLine("Ooops, something wrent wrogn \n" + e);
                    loop = false;
                }
                if (gotData)
                {
                    //converting bytes to int, sending DMX Values
                    int channel = Convert.ToInt32(incomingValues[0]);
                    int value = Convert.ToInt32(incomingValues[1]);
                    DmxInterface.SetData(channel, value);
                    Console.WriteLine("Received Data... \n Channel: " + channel + " Value: " + value);
                }
            }
            else
            {
                //exiting loop if connection is lost
                Console.WriteLine("connection lost");
                Program.ServerStopped = true;
                loop = false;
            }
        }
    }
}

}

0 个答案:

没有答案