连接 Python 服务器和 C# 客户端

Connecting a Python Server and C# Client

我正在尝试使用 C# GUI 程序单击按钮向我的 Raspberry pi(Python 服务器)发送文本消息。我的 python 服务器应该打印我的短信..我可以编译和 运行 这两个程序..没有任何错误消息..但是我没有在我的 Raspberry pi 上收到任何消息并且文本数据没有打印在我的 Raspberry Pi的终端机。

这是 C# 客户端代码:

public partial class MainWindow : Window
    {
        bool button1WasClicked = false;

        public MainWindow()
        {
            InitializeComponent();
        }

        UdpClient client = new UdpClient();

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            if (button1WasClicked)
            {
                byte[] a1 = Encoding.ASCII.GetBytes(textbox.Text);
                client.Send(a1, a1.Length);
                button1WasClicked = false;                  
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Send data when button is clicked
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipbox.Text), int.Parse(portbox.Text)); // endpoint where server is listening
            client.Connect(ep);
            button1WasClicked = true;
            byte[] a1 = Encoding.ASCII.GetBytes(textbox.Text);
            client.Send(a1, a1.Length);
        }
    }

我的python服务器代码:

# Echo server program
import socket
import RPi.GPIO as GPIO
import os
import sys

HOST = '192.168.1.12'  # Symbolic name meaning all available interfaces
PORT = 9050        # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)

while 1:
    data = conn.recv(1024)
    if not data: break
    if data =="1":
        GPIO.output(7,True)
    if data =="2":
        GPIO.output(7,False)
    conn.sendall(data)
    os.system(str(data)) //prints data on the terminal
    conn.sendall(data)
conn.close()

您的服务器使用 TCP (SOCK_STREAM),但您的客户端使用 UDP - 两者需要使用相同的协议。