【问题标题】:How do you send messages to Async Sockets consecutively - (Python and C#)如何将消息连续发送到异步套接字 - (Python 和 C#)
【发布时间】:2021-04-07 09:21:06
【问题描述】:

我可能犯了一个新手错误,但我刚刚开始尝试在我的 PC 和 Raspberry Pi 之间进行本地 TCP 通信。 我的服务器在我的 Raspberry Pi 上运行(在 python 中),我的 PC 上的客户端(用 C# 编写)能够连接到 RPi,正确发送一组数据,然后不再发送,除非建立新的连接. 我只是试图通过连接多次发送数字 2(例如,我按下连接按钮,然后我可以多次按下发送按钮,服务器将多次接收数据。 任何帮助表示赞赏。

客户端代码(C#):

public ClientForm()
        {
            ipAddress = IPAddress.Parse("192.168.0.98");
            port = 3333;
            InitializeComponent();
        }

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

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.BeginConnect(new IPEndPoint(ipAddress, port), new AsyncCallback(this.connectCallback), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = { 2 };
                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)
        {
            clientSocket.EndSend(AR);
        }

服务器代码(Python 3):

import socket
port = 3333
ipAddress = '192.168.0.98'
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

serverSocket.bind((ipAddress, port))

while True:
    serverSocket.listen(0)
    clientsocket, address = serverSocket.accept()
    received = int.from_bytes(clientsocket.recv(1), 'big')
    print(received)

【问题讨论】:

    标签: python c# sockets asynchronous


    【解决方案1】:

    我认为问题出在你的 python 服务器上。

    accept 函数会阻止您的循环,直到客户端向服务器请求连接。

    在您连接客户端后,您的服务器会接受连接,但循环之后,服务器会阻塞,直到它可以接受另一个连接。这就是它无法接收多个数据的原因。

    我看到了两种遇到这个问题的方法:

    使用select 函数,因此您可以立即使用acceptreceive

    使用threads 这样您就可以将acceptreceive 作为并行任务

    【讨论】:

      猜你喜欢
      • 2017-06-27
      • 2015-05-17
      • 1970-01-01
      • 2017-05-30
      • 2020-08-29
      • 2018-03-30
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      相关资源
      最近更新 更多