【发布时间】: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