服务器调用accept方法而不是receive方法

时间:2019-06-01 15:16:19

标签: c# sockets server client

我想编写我的第一个客户端-服务器程序。所以我搜索了教程/技巧。我找到了本教程:https://www.youtube.com/watch?v=xgLRe7QV6QI,现在的问题是,当我与客户端发送消息时,服务器调用了accept方法而不是视频中的receive方法。

没有Try-Catch,Visual Studio说:System.ArgumentException:“ IAsyncResult对象不是从此类的相应异步方法返回的。 Arg_ParamName_Name“

使用Try-Catch:System.ArgumentException:此类未从相应的异步方法返回IAsyncResult对象。 参数名称:asyncResult    在System.Net.Sockets.Socket.EndAccept(Byte []&缓冲区,Int32&bytesTransferred,IAsyncResult asyncResult)    在System.Net.Sockets.Socket.EndAccept(IAsyncResult asyncResult)    在F:\ Programmierung \ C#\ workspace \ Client-Server \ Client-Server \ Program.cs:line 33的Client_Server.Program.AcceptCallback(IAsyncResult AR)中

最后一个'at'表示问题出在第33行

服务器:


    class Program {
        private static Thread mainThread;

        private static byte[] _buffer = new byte[1024];
        private static List<Socket> _clientSockets = new List<Socket>();
        private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        static void Main(string[] args) {
            Console.Title = "Server";
            SetupServer();
            Console.ReadLine(); 
        }

        private static void SetupServer() {
            Console.WriteLine("Starting server");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
            _serverSocket.Listen(5); 
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);

        }
        private static void AcceptCallback(IAsyncResult AR) {
            Console.WriteLine("Accept");
            try {
                Socket socket = _serverSocket.EndAccept(AR);
                _clientSockets.Add(socket);
                Console.WriteLine("A client has connected to the server");
                socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(AcceptCallback), socket);
                _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
            }
            catch(Exception e) {
                Console.WriteLine(e);
            }
        }

        private static void ReceiveCallback(IAsyncResult AR) {
            Console.WriteLine("Received");
            Socket socket = (Socket)AR.AsyncState;
            int received = socket.EndReceive(AR);
            byte[] dataBuf = new byte[received];
            Array.Copy(_buffer, dataBuf, received);

            String text = Encoding.ASCII.GetString(dataBuf);
            Console.WriteLine("Message received: " + text);

            String response = String.Empty;

            if (!text.ToLower().Equals("/time")) {
                response = "Invalid Request";
            }
            else {
                response = DateTime.Now.ToLongTimeString();
            }

            byte[] data = Encoding.ASCII.GetBytes(response);
            socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
        }

        private static void SendCallback(IAsyncResult AR) {
            Socket socket = (Socket)AR.AsyncState;
            socket.EndSend(AR);
        }
    }

客户:

    class FirstClient{
        private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        static void Main(String[] args) {
            Console.Title = "Client";
            LoopConnect();
            SendLoop();
            Console.ReadLine();
        }

        private static void SendLoop() {
            while(true){
                Console.Write("Enter a request: ");
                String requests = Console.ReadLine();
                byte[] buffer = Encoding.ASCII.GetBytes(requests);
                _clientSocket.Send(buffer);
                byte[] receivedBuffer = new byte[1024];
                int rec = _clientSocket.Receive(receivedBuffer);
                byte[] data = new byte[rec];
                Array.Copy(receivedBuffer, data, rec);
                Console.WriteLine("Received: " + Encoding.ASCII.GetString(data));
            }
        }

        private static void LoopConnect() {

            int attemps = 0;

            while (!_clientSocket.Connected) {
                try {
                    attemps++;
                    _clientSocket.Connect(IPAddress.Loopback, 100);
                }
                catch (SocketException) { 
                Console.Clear();
                    Console.WriteLine("Connection attemps: " + attemps);
                }
            }

            Console.Clear();
            Console.WriteLine("Connected to server");
        }
    }
}

我希望有人能帮助我。

感谢所有想帮助我的人!

0 个答案:

没有答案