TCP套接字客户端\服务器请求响应

问题描述

我正在开发.Net 4.5.2 Windows TCP套接字主服务器\客户端消息传递解决方案。该解决方案在大多数情况下都有效。然而,我所需要的服务器选择了发送按钮时,响应消息发送回客户端。当选择了连接按钮主确实成功响应消息发送回客户端。我曾多次试图发送响应消息发送回从当选择了发送按钮主客户端应用程序,但我已经无法使其正常工作。我正在寻找帮助,以使我再次前进。不想继续转动我的轮子,没有进步。先谢谢您的帮助。请在下面找到服务器和客户端解决方案:

服务器代码:

 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 static void ShowErrorDialog(string message)
        {
            MessageBox.Show(message,Application.ProductName,MessageBoxButtons.OK,MessageBoxIcon.Error);
        }

        private void StartServer()
        {
            try
            {
                IPAddress ipAddress = IPAddress.Parse("192.168.1.124");
                serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                serverSocket.Bind(new IPEndPoint(ipAddress,4545));
                serverSocket.Listen(10);
                serverSocket.BeginAccept(AcceptCallback,null);
            }
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }

        private void AcceptCallback(IAsyncResult AR)
        {
            try
            {
                clientSocket = serverSocket.EndAccept(AR);
                buffer = new byte[clientSocket.ReceiveBufferSize];
                var sendData = Encoding.ASCII.GetBytes("Hello");
                clientSocket.BeginSend(sendData,sendData.Length,SocketFlags.None,SendCallback,null);
                clientSocket.BeginReceive(buffer,buffer.Length,ReceiveCallback,null);
                serverSocket.BeginAccept(AcceptCallback,null);
            }
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }

        private void SendCallback(IAsyncResult AR)
        {
            try
            {
                clientSocket.EndSend(AR);
            }
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }

        private void ReceiveCallback(IAsyncResult AR)
        {
            try
            {
                Socket current = (Socket)AR.AsyncState;
                int received = clientSocket.EndReceive(AR);

                if (received == 0)
                {
                    return;
                }

                PersonPackage person = new PersonPackage(buffer);
                SubmitPersonToDataGrid(person);

                clientSocket.BeginReceive(buffer,null);

                //Added BeginSend which answered my question.  Simple enough fix.  Thanks for looking...
                byte[] sendData = Encoding.ASCII.GetBytes(person.Name);
                clientSocket.BeginSend(sendData,null);
            }
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }

客户代码:

 public partial class ClientForm : Form
    {
        private Socket clientSocket;
        private byte[] buffer;

        public ClientForm()
        {
            InitializeComponent();
        }

        private static void ShowErrorDialog(string message)
        {
            MessageBox.Show(message,MessageBoxIcon.Error);
        }

        private void ReceiveCallback(IAsyncResult AR)
        {
            try
            {
                int received = clientSocket.EndReceive(AR);

                if (received == 0)
                {
                    return;
                }

                string message = Encoding.ASCII.GetString(buffer).TrimEnd('\0');

                Invoke((Action) delegate
                {
                  textBoxEmployee.Text = string.Empty;
                  textBoxEmployee.Text = "Server says: " + message +  " Paul";
                });

                clientSocket.BeginReceive(buffer,null);
            }

            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }

        private void ConnectCallback(IAsyncResult AR)
        {
            try
            {
                clientSocket.EndConnect(AR);
                UpdateControlStates(true);
                buffer = new byte[clientSocket.ReceiveBufferSize];
                clientSocket.BeginReceive(buffer,null);
            }
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }

        private void SendCallback(IAsyncResult AR)
        {
            try
            {
                clientSocket.EndSend(AR);
            }
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }

        private void UpdateControlStates(bool toggle)
        {
            Invoke((Action)delegate
            {
                buttonSend.Enabled = toggle;
                buttonConnect.Enabled = !toggle;
                labelIP.Visible = textBoxAddress.Visible = !toggle;
            });
        }

        private void buttonSend_Click(object sender,EventArgs e)
        {
            try
            {
                PersonPackage person = new PersonPackage(checkBoxMale.Checked,(ushort)numberBoxAge.Value,textBoxEmployee.Text);
                byte[] buffer = person.ToByteArray();
                clientSocket.BeginSend(buffer,null);
            }
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
                UpdateControlStates(false);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
                UpdateControlStates(false);
            }
        }

        private void buttonConnect_Click(object sender,EventArgs e)
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork,ProtocolType.Tcp);
                // Connect to the specified host.
                var endPoint = new IPEndPoint(IPAddress.Parse(textBoxAddress.Text),4545);
                clientSocket.BeginConnect(endPoint,ConnectCallback,null);
            }
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }
    }

解决方法

发现问题。向服务器BeginSend方法中添加了SendCallBack。代码已更新并且可以使用...

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...