TCP / IP客户端服务器在不同网络上的通信C#

时间:2019-04-23 13:37:06

标签: c# .net sockets xamarin

我尝试通过发送一个小的请求来获取时间,以使我的客户端和服务器进行通信,但是只有当它们在同一网络中时,它才能工作。 我的客户是Xamarin应用程序 而我的服务器是控制台应用程序。

就现在而言,我可以让他们在同一网络上进行通信,但是对于我的项目,他们必须通过Disant进行通信。我试图阅读一些.NET.Sockets文档,但找不到适合我问题的正确答案。

客户代码

protected void OnButtonClicked(object sender, EventArgs args)
        { int attempts = 0;


           while (!clientSocket.Connected)
            {
                attempts++;
                gettext.Text = "Connection attempts:" + attempts.ToString();
                clientSocket.Connect("192.168.0.107", 100);
            }
            gettext.Text = "Connected";
            SendLoop();
        }



private  void SendLoop()
        {

                gettext.Text = "get time";
                string req = gettext.Text;
                byte[] buffer = Encoding.ASCII.GetBytes(req);
                clientSocket.Send(buffer);
                byte[] BuffRec = new byte[1024];
                int rec = clientSocket.Receive(BuffRec);
                byte[] data = new byte[rec];
                Array.Copy(BuffRec, data, rec);
                gettext.Text = "Received:" + Encoding.ASCII.GetString(data);

        }


服务器代码

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Server
{
    class Server
    {
        private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static readonly List<Socket> clientSockets = new List<Socket>();
        private const int BUFFER_SIZE = 2048;
        private const int PORT = 100;
        private static readonly byte[] buffer = new byte[BUFFER_SIZE];

        static void Main()
        {
            Console.Title = "DENM";
            SetupServer();
            Console.ReadLine(); // When we press enter close everything
            CloseAllSockets();
        }

        private static void SetupServer()
        {
            Console.WriteLine("Setting up server...");
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
            serverSocket.Listen(0);
            serverSocket.BeginAccept(AcceptCallback, null);
            Console.WriteLine("Server setup complete");

            //Using the AddressFamily, SocketType, and ProtocolType properties.
            Console.WriteLine("I just set the following properties of socket: " + "\nAddress Family = " + serverSocket.AddressFamily.ToString() + "\nSocketType = " + serverSocket.SocketType.ToString() + "\nProtocolType = " + serverSocket.ProtocolType.ToString());            Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)serverSocket.RemoteEndPoint).Address.ToString()) + "on port number " + ((IPEndPoint)serverSocket.RemoteEndPoint).Port.ToString());

        }

        /// <summary>
        /// Close all connected client (we do not need to shutdown the server socket as its connections
        /// are already closed with the clients).
        /// </summary>
        private static void CloseAllSockets()
        {
            foreach (Socket socket in clientSockets)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }

            serverSocket.Close();
        }

        private static void AcceptCallback(IAsyncResult AR)
        {
            Socket socket;

            try
            {
                socket = serverSocket.EndAccept(AR);
            }
            catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
            {
                return;
            }

            clientSockets.Add(socket);
            socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
            Console.WriteLine("Client connected, waiting for request...");
            serverSocket.BeginAccept(AcceptCallback, null);
        }

        private static void ReceiveCallback(IAsyncResult AR)
        {
            Socket current = (Socket)AR.AsyncState;
            int received;

            try
            {
                received = current.EndReceive(AR);
            }
            catch (SocketException)
            {
                Console.WriteLine("Client forcefully disconnected");
                // Don't shutdown because the socket may be disposed and its disconnected anyway.
                current.Close();
                clientSockets.Remove(current);
                return;
            }

            byte[] recBuf = new byte[received];
            Array.Copy(buffer, recBuf, received);
            string text = Encoding.ASCII.GetString(recBuf);
            Console.WriteLine("Received Text: " + text);

            if (text.ToLower() == "get time") // Client requested time
            {
                Console.WriteLine("Text is a get time request");
                byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
                current.Send(data);
                Console.WriteLine("Time sent to client");
            }
            else if (text.ToLower() == "exit") // Client wants to exit gracefully
            {
                // Always Shutdown before closing
                current.Shutdown(SocketShutdown.Both);
                current.Close();
                clientSockets.Remove(current);
                Console.WriteLine("Client disconnected");
                return;
            }
            else
            {
                Console.WriteLine("Text is an invalid request");
                byte[] data = Encoding.ASCII.GetBytes("Invalid request");
                current.Send(data);
                Console.WriteLine("Warning Sent");
            }

            current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
        }
    }
}

我希望即使我的移动应用位于其他网络上,也可以使其与服务器通信

0 个答案:

没有答案