C# 异步客户机-服务器通信问题

C# 异步客户机-服务器通信问题,c#,asynchronous,client-server,C#,Asynchronous,Client Server,我是一名编程新手,正在开发一个异步客户机-服务器应用程序。 我可以从客户机向服务器发送消息,但是当我接收到数据到服务器OnDataReceived方法并尝试将相同的数据发送回客户机进行测试时,我就不能了。 我不确定我还需要提供什么信息,所以请让我知道,我不想含糊其辞 服务器代码 public void OnDataReceived(IAsyncResult asyncResult) { try { SocketPacket sock

我是一名编程新手,正在开发一个异步客户机-服务器应用程序。 我可以从客户机向服务器发送消息,但是当我接收到数据到服务器OnDataReceived方法并尝试将相同的数据发送回客户机进行测试时,我就不能了。 我不确定我还需要提供什么信息,所以请让我知道,我不想含糊其辞

服务器代码

public void OnDataReceived(IAsyncResult asyncResult)
    {
        try
        {
            SocketPacket socketData = (SocketPacket)asyncResult.AsyncState;
            int iRx = 0;
            iRx = socketData.currentSocket.EndReceive(asyncResult);
            char[] chars = new char[iRx];
            Decoder decoder = Encoding.UTF8.GetDecoder();
            int charLen = decoder.GetChars(socketData.dataBuffer, 0, iRx, chars, 0);
            String receivedData = new String(chars);

            //BroadCast(receivedData);

            this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => lbxMessages.Items.Add(receivedData)));

            //Updated Code
            this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => broadcast(receivedData)));

            WaitForData(socketData.currentSocket);


        }
        catch (ObjectDisposedException)
        {
            System.Diagnostics.Debugger.Log(0, "1", "\n OnDataRecieved: Socket has been closed\n");
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }

public class SocketPacket
    {
        public Socket currentSocket;
        public byte[] dataBuffer = new byte[50];//allowing the 50 digist to be sent at once
    }

    private void WaitForData(Socket socket)
    {
        try
        {
            if (workerCallBack == null)
            {
                workerCallBack = OnDataReceived;
            }
            SocketPacket sckPack = new SocketPacket();
            sckPack.currentSocket = socket;
            socket.BeginReceive(sckPack.dataBuffer, 0, sckPack.dataBuffer.Length, SocketFlags.None, workerCallBack, sckPack);
        }
        catch(SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }
根据Andrew的回复更新

我有一个方法,当连接客户端时将调用该方法

private void OnClientConnect(IAsyncResult asyncResult)
    {
        try
        {
            //Here we complete/end the Beginaccept() asynchronous call by
            //calling EndAccept() - which returns the reference to a new socket object
            workerSocket[clientCount] = listenSocket.EndAccept(asyncResult);

            //Let the worker socket do the further processing for the just connected client
            WaitForData(workerSocket[clientCount]);

            //Now increment the client count
            ++clientCount;

            if (clientCount<4)//allow max 3 clients
            {
                //Adds the connected client to the list
                connectedClients.Add(listenSocket);
                String str = String.Format("Client # {0} connected", clientCount);                   

                this.Dispatcher.Invoke((Action)(() =>
                {
                    //Display this client connection as a status message on the GUI
                    lbxMessages.Items.Add(str);
                    lblConnectionStatus.Content =clientCount + " Connected";
                }));

                //Since the main Socket is now free, it can go back and wait for
                //other clients who are attempting to connect
                listenSocket.BeginAccept(OnClientConnect, null);
            }
        }
        catch (ObjectDisposedException)
        {
            System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
        }
        catch (SocketException)
        {
            HandleClientDisconnect(listenSocket);
        }
    }

服务器端TCP通信涉及两个套接字。第一个套接字是侦听套接字,您应该仅在接受新请求时使用它。然后,每次您接受来自客户端的新请求时,每个连接都会得到另一个套接字


您试图通过侦听套接字发送数据,但不是通过您接受的套接字。

Sergey说得对。如果您希望一台服务器处理多个客户端,那么您需要某种类型的ServerTerminal类,它可以侦听新的连接,然后设置某种类型的connectedclient类来处理该套接字的IO。OnDataReceived方法将位于connectedclient类中

在套接字接受例程中,它应该类似于:

private void OnClientConnection(IAsyncResult asyn)
    {
        if (socketClosed)
        {
            return;
        }

        try
        {
            Socket clientSocket = listenSocket.EndAccept(asyn);

            ConnectedClient connectedClient = new ConnectedClient(clientSocket, this, _ServerTerminalReceiveMode);

            connectedClient.StartListening();

在accept例程中,您被传递了一个套接字-我将这个clientSocket命名为。这是您要写入的套接字,而不是侦听套接字。

不能将数据发送回客户端是什么意思?你收到了什么错误?顺便说一句,如果您刚开始编程,请先从同步版本开始,然后再转到异步版本。错误读取“由于套接字未连接,因此不允许发送或接收数据的请求,并且在使用sendto调用发送数据报套接字时未提供地址”读取更新,我认为您应该向workerSocket[ClientCount]中保存的套接字进行写入。关于Clientcount,与您的问题无关,但您可能希望调试如何使用它-您似乎正在向数组写入数据-workerSocket[Clientcount];然后你再递增,然后可能/可能不使用它。在我看来,第四个客户端将添加到WorkerSocket;还发布了WaitForData,但没有添加到connectedClient等。我有一个处理客户端连接的方法,如果这就是你所说的。
private void OnClientConnection(IAsyncResult asyn)
    {
        if (socketClosed)
        {
            return;
        }

        try
        {
            Socket clientSocket = listenSocket.EndAccept(asyn);

            ConnectedClient connectedClient = new ConnectedClient(clientSocket, this, _ServerTerminalReceiveMode);

            connectedClient.StartListening();