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

本文关键字:数据 不能 服务器 客户端 | 更新日期: 2023-09-27 18:02:50

我有一个winform服务器和一个客户程序。两者连接,客户端可以向服务器发送数据,服务器接收数据。但是当服务器发送数据时,客户端无法接收。

下面是客户端接收数据的代码:
//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);
        }
    }

,完整的服务器代码(接收+发送)是:

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

服务器正确接收到数据,但是我不知道为什么客户端不能从服务器接收到数据。是服务器发送的方式不对吗?还是客户接收的方式不对?我必须为客户端设置IP地址吗?

欢迎任何帮助....

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

你误解了套接字的用法。套接字有一个读通道和一个写通道。两个通道都是相互隔离的。看看你的客户端代码,你使用'serverSocket'来监听传入的数据,而你使用'clientSocket'来发送数据到服务器。相反,您应该使用同一个套接字的读和写通道。

说明:TCP套接字已连接。这意味着对于每个套接字,在使用该套接字之前都需要建立连接。监听一个套接字意味着你期望被连接。在你的客户端,'clientSocket'连接到服务器,但'serverSocket'从来没有连接到服务器也不是服务器连接到客户端(它不应该)。