如何连续向异步套接字发送消息-(Python和C#)
我可能犯了一个新手错误,但我刚刚开始尝试在我的电脑和Raspberry Pi之间进行本地TCP通信。 我的服务器运行在我的Raspberry Pi(python)上,我的PC上的客户端(用C#编写)能够连接到RPi,正确发送一组数据,然后不再发送,除非建立新连接。 我只是尝试多次通过连接发送数字2(例如,我按下connect按钮,然后我可以多次按下send按钮,服务器将多次接收数据)。 感谢您的帮助 客户代码(C#): 服务器代码(Python 3):如何连续向异步套接字发送消息-(Python和C#),python,c#,sockets,asynchronous,Python,C#,Sockets,Asynchronous,我可能犯了一个新手错误,但我刚刚开始尝试在我的电脑和Raspberry Pi之间进行本地TCP通信。 我的服务器运行在我的Raspberry Pi(python)上,我的PC上的客户端(用C#编写)能够连接到RPi,正确发送一组数据,然后不再发送,除非建立新连接。 我只是尝试多次通过连接发送数字2(例如,我按下connect按钮,然后我可以多次按下send按钮,服务器将多次接收数据)。 感谢您的帮助 客户代码(C#): 服务器代码(Python 3): 我认为问题来自您的python服务器 ac
我认为问题来自您的python服务器
accept
功能会阻止循环,直到客户端请求服务器连接
连接客户端后,服务器会接受连接,但之后的循环会阻止服务器,直到它可以接受另一个连接。这就是它无法接收多个数据的原因
我认为有两种方法可以解决这个问题:
使用选择
功能,您可以立即接受
或接收
使用线程
,以便可以接受
和接收
作为并行任务
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);
}
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)