c#异步套接字-获取数据

本文关键字:获取 数据 套接字 异步 | 更新日期: 2023-09-27 18:01:42

我正在构建一个简单的服务器,它包含一些信息,并将使用异步套接字来获得N个连接(我真的不知道有多少,它们可以从50到1000不等)。

此服务器的主要目的是"验证"连接的客户端的文件完整性和版本,如果需要,将更新的文件发送给他们,以便他们可以打补丁。

现在,我正在让我的套接字运行,我可以在控制台中显示数据,一切都很好,问题是,我最重要的变量是我的'DownloadServer'类,而我的套接字函数是在一个名为'ServerSocket'的类。

我的问题是,我怎么能访问数据在DownloadServer(其中包含一个实例ServerSocket)当说的信息被请求到我的套接字。我不能返回与异步回调接收的数据(因为它们必须是空的),所以什么是最好的方法去做这个?

这是我的套接字代码,它只接收客户端并打印发送的数据。我想做的是访问接收到的信息(同样,例如命令)并返回到客户端的请求信息,例如,如果收到的消息是"GetFileVersion",服务器应该回复它包含的变量的值(这是一个名为FILEVERSION的全局变量),作为问题,我似乎找不到访问该变量的方法。

class ServerSocket
 {
    private Socket _socket;
    private byte[] _buffer;
    public ServerSocket()
    {
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    }
    public void bind(int port)
    {
        _socket.Bind(new IPEndPoint(IPAddress.Any, port));
    }
    public void Listen(int backlog)
    {
        _socket.Listen(backlog);
    }
    public void Accept()
    {
        _socket.BeginAccept(AcceptCallBack, null);
    }
    private void AcceptCallBack(IAsyncResult ar)
    {
        Socket clientSocket = _socket.EndAccept(ar);
        Accept();
        IPEndPoint clientEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
        Console.WriteLine("Client Connected: {0}",clientEndPoint.Address.ToString());
        _buffer = new byte[2048];
        clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceivedCallback, clientSocket);

    }
    private void ReceivedCallback(IAsyncResult ar)
    {
        try
        {
            Socket clientSocket = ar.AsyncState as Socket;
            int size = clientSocket.EndReceive(ar);
            byte[] packet = new byte[size];
            Array.Copy(_buffer, packet, packet.Length);
            String data = System.Text.Encoding.ASCII.GetString(packet, 0, packet.Length);

        }
        catch (Exception ex)
        {
            ;
        }
    }

 }
}

提前感谢!

编辑:我想做的是类似String commandReceived = socket. receive()(就像您对同步套接字所做的那样),或者以某种方式访问通过套接字接收的命令。

class DownloadServer
{
    private static String UPDATEPATH="";
    private static int FILEVERSION;
    private static string ROOTPATH = "";
    private String SQLUsername = "";
    private String SQLPassword = "";
    private String AccountDB = "";
    private String ServerName = "";
    private SqlConnection sqlConn;
//some logic methods
static void Main(string[] args){
ServerSecurity serverSecurity = new ServerSecurity();
        ServerSocket serverSocket = new ServerSocket();
        serv.Initialize();
        serverSecurity.Initialize();
        serverSocket.bind(15779);
        serverSocket.Listen(1000);
        serverSocket.Accept();
        while (true)
        {
            Console.WriteLine("Input the command:");
            var Input = Console.ReadLine();
            if (Input == "Update")
            {
                serv.prepareUpdate();
            }
            else if (Input == "Exit")
            {
                Environment.Exit(0);
            }
            else if (Input == "TestEncryption")
            {
                Console.WriteLine("Enter the text to be encrypted:");
                String plainText = Console.ReadLine();
                Console.WriteLine("Original Text = {0}", plainText);
                Console.WriteLine("Encrypted Text = {0}", serverSecurity.Encrypt(plainText));
                Console.WriteLine("Decrypted Text = {0}", serverSecurity.Decrypt(serverSecurity.Encrypt(plainText)));
            }
        }
    }

c#异步套接字-获取数据

添加你的DownloadServer类:

Socket NewSocket;
byte[] buffer = new buffer [1024];
NewSocket = serverSocket.Accept();

然后开始Receive from this NewSocket:

void Receive()
{
 NewSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, r);
}

 private void ReceiveCallback(IAsyncResult ar)
        {
            Socket CurrentClient = (Socket)ar.AsyncState;
            int Received;
            try { Received = CurrentClient.Receive(buffer); }
            catch
            {
                return;
            }

            byte[] _buffer = new byte[Received];
            Array.Copy(buffer, _buffer, Received);
            string _Text = Encoding.Unicode.GetString(_buffer);
           if(_Text == "GetVersion")
            byte[] infoVersion = Encoding.Encoding.Default.GetBytes(FILEVERSION);
              CurrentClient .Send(infoVersion )
}

这看起来像是一个经典的设计问题,你试图给一个类太多的责任。在SOLID设计中,每个类应该有一个单独的职责。SocketServer将只负责创建套接字和发送/接收数据。下载服务器将负责创建要发送的数据。另一个类ValidationServer负责通过SocketServer请求数据并对其进行解析。第三个类(如果您愿意,也可以称为控制器)将负责协调调用并在这些类之间传递数据。通过这种方式,你的SocketServer和DownloadServer将被解耦,并且不需要彼此的变量。