简体   繁体   English

客户端不能接收从服务器发送的数据,而只能发送数据?

[英]Client cannot recieve data sent from server but can send data only?

I have a winform server and a client programs. 我有一个Winform服务器和一个客户端程序。 both are connected, the client can send data to server and the server receives. 两者都已连接,客户端可以将数据发送到服务器,服务器可以接收。 but when the server sends data, the client cannot receive. 但是当服务器发送数据时,客户端无法接收。

here is the code for client to receive data: 这是客户端接收数据的代码:

//RECIEVE PART
 private Socket _clientSocket; // We will only accept one socket

    private byte[] _buffer;

    public Form1()
    {
        InitializeComponent();
        StartRecieve();
    }


    #region Receiving Data
    private void StartRecieve()
    {
        try
        {
            _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
           // _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
            _serverSocket.Listen(10);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void AcceptCallback(IAsyncResult AR)
    {
        try
        {
            _clientSocket = _serverSocket.EndAccept(AR);
            _buffer = new byte[_clientSocket.ReceiveBufferSize];
            _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ReceiveCallback(IAsyncResult AR)
    {
        try
        {
            int received = _clientSocket.EndReceive(AR);
            Array.Resize(ref _buffer, received); // Shrink buffer to trim null characters
            string text = Encoding.ASCII.GetString(_buffer);
            Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize); // Regrow buffer
            //AppendToTextBox(text);
            MessageBox.Show(text);
            // Start receiving data again
            _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    #endregion

    #region Display
    /// <summary>
    /// Provides a thread safe way to append text to the textbox
    /// </summary>
    private void AppendToTextBox(string text)
    {
        MethodInvoker invoker = new MethodInvoker(delegate
        {
            // Add two new lines afterwards
            TboxDisp.Text += text + "\r\n" + "\r\n";
        });

        this.Invoke(invoker);
    }

    #endregion
//Connection Part
 private void BtnConnect_Click(object sender, EventArgs e)
    {
        try
        {
            string ip = TboxIP.Text;
            int port = int.Parse(TboxPort.Text);
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // Connect to the  host
            _clientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port),
                                            new AsyncCallback(ConnectCallback), null);

            if (SocketConnected(_clientSocket) == true)
            {
                lblstatus.Text = "Establishing Connection to " + ip;
                lblstatus2.Text = "Connection Established";
            }

           // Connect1(ip, port);

        }
        catch (SystemException ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

    //ends bending requests
    private void ConnectCallback(IAsyncResult AR)
    {
        try
        {
            _clientSocket.EndConnect(AR);
            EnableSearchButton();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    //Enables the button search
    private void EnableSearchButton()
    {
        MethodInvoker invoker = new MethodInvoker(delegate
        {
            BtnSearch.Enabled = true;
        });

        this.Invoke(invoker);
    }

    #endregion

    private void BtnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            // Serialize the textBoxes text before sending
           // byte[] buffer = Encoding.ASCII.GetBytes(textBox.Text);
            string command = "HELOTAGP/1.1\n";
            byte[] buffer = Encoding.ASCII.GetBytes(command);
            _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    //Ends pending asynchronous send
    private void SendCallback(IAsyncResult AR)
    {
        try
        {
            _clientSocket.EndSend(AR);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

and the complete server code (receive + sending) is : 完整的服务器代码(接收+发送)为:

 public partial class ServerForm : Form
{
    private Socket _serverSocket;
    private Socket _clientSocket; // We will only accept one socket
    private byte[] _buffer;

    public ServerForm()
    {

        InitializeComponent();
        StartServer();
    }


    private void StartServer()
    {
        try
        {
            _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
            _serverSocket.Listen(10);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void AcceptCallback(IAsyncResult AR)
    {
        try
        {
            _clientSocket = _serverSocket.EndAccept(AR);
            _buffer = new byte[_clientSocket.ReceiveBufferSize];
            _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ReceiveCallback(IAsyncResult AR)
    {
        try
        {
            int received = _clientSocket.EndReceive(AR);
            Array.Resize(ref _buffer, received); // Shrink buffer to trim null characters
            string text = Encoding.ASCII.GetString(_buffer);
            Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize); // Regrow buffer


            AppendToTextBox(text);
            // Start receiving data again
            _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    /// <summary>
    /// Provides a thread safe way to append text to the textbox
    /// </summary>
    private void AppendToTextBox(string text)
    {
        MethodInvoker invoker = new MethodInvoker(delegate
            {
                // Add two new lines afterwards
                textBox.Text += text + "\r\n" + "\r\n";
            });

        this.Invoke(invoker);
    }


    //sending data


    private void BtnSend_Click(object sender, EventArgs e)
    {
        try
        {
            // Serialize the textBoxes text before sending
            string command = "Test";
            byte[] buffer = Encoding.ASCII.GetBytes(command);
            _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void SendCallback(IAsyncResult AR)
    {
        try
        {
            _clientSocket.EndSend(AR);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

the server receives the data correctly, but i don't know why the client cannot receive from the server. 服务器正确接收数据,但是我不知道为什么客户端无法从服务器接收数据。 Is it the way server sending is wrong? 是服务器发送错误的方式吗? or the way client receiving is wrong? 还是客户接收方式错误? Do i have to set an IP address for the client? 我必须为客户端设置IP地址吗?

Any help is appreciated.... 任何帮助表示赞赏。

You misunderstand the use of Sockets. 您误解了套接字的使用。 A socket has both a read channel and a write channel. 套接字同时具有读取通道和写入通道。 Both channels are isolated from each other. 两个通道相互隔离。 Looking at your client code, you use use a 'serverSocket' to listen for incoming data while you use a 'clientSocket' to send data to the server. 查看您的客户端代码,使用“ serverSocket”侦听传入的数据,而使用“ clientSocket”将数据发送到服务器。 Instead, you should employ the read and write channels of one and the same socket. 相反,您应该使用一个插座和同一插座的读取和写入通道。

As a clarification: a TCP socket is connected. 作为澄清:连接了TCP套接字。 That means that for each socket, a connection is required before the socket can be used. 这意味着对于每个插座,必须先进行连接,然后才能使用该插座。 Listening on a socket means that you're expecting to be connected to. 在套接字上侦听意味着您希望连接到该套接字。 In your client, the 'clientSocket' is connecting to the server but the 'serverSocket' is never connected to the server nor is the server ever connecting to the client (which it shouldn't). 在您的客户端中,“ clientSocket”正在连接到服务器,但是“ serverSocket”从不连接到服务器,服务器也从未连接到客户端(不应该)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法从C#TCP服务器接收数据 - cannot recieve data from c# tcp server 连接到telnet服务器并发送/接收数据 - Connecting to telnet server and send/recieve data 如何通过 C# windows 应用程序发送数据并使用 TCP/IP 协议从 android 客户端接收数据 - How to send data by C# windows application and recieve it from android Client using TCP/IP protocal 无法通过 WCF 从客户端向服务器发送流数据 - Can't send streamed data from client to server via WCF 无法读取从 python 上的 TCP 客户端发送到 ZD7EFA19FBE7D3972FD5ADB6024223D74 中的 TCP 服务器的数据 - Cannot read data sent from TCP client on python to TCP server in C# 如何从服务器读取数据并将其发送到客户端? - How to read and send data to client from server? 将数据从服务器发送到特定客户端 - Send data from server to a specific client 将数据从服务器发送回客户端 - Send data from server back to the client 当我从客户端向服务器发送命令时,仅当请求发送两次时,客户端才会收到响应 - When I send a command to server from client , the client receives the response only if the request is sent twice 是否可以将ReactJS服务器渲染与客户端发送的数据一起使用? - Is it possible to use ReactJS server rendering with data sent from the client?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM