1

我是编程新手,我正在开发一个异步客户端服务器应用程序。我可以从客户端向服务器发送消息,但是当我将数据接收到服务器(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);
        }
    }

更新以回应安德鲁的回复

我有一个连接客户端时将调用的方法

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);
        }
    }

(更新)服务器收到的广播消息的添加方法返回给客户端

public void broadcast(string msg)
    {
        //foreach (Socket item in connectedClients)
        //{
        Socket broadcastSocket;
        broadcastSocket = workerSocket[0]; //sends message to first client connected
        byte[] broadcastBytes = null;
        broadcastBytes = Encoding.ASCII.GetBytes(msg);
        broadcastSocket.Send(broadcastBytes);
        //}
    }
4

2 回答 2

0

谢尔盖说得对。如果您希望一台服务器处理多个客户端,那么您将需要某种可以侦听新连接的 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();

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

于 2012-12-05T00:21:26.983 回答
0

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

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

于 2012-12-04T18:56:16.570 回答