繁体   English   中英

连接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-两者都需要使用相同的协议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM