【问题标题】:Socket between C# (With WPF) Server and Python ClientC#(使用 WPF)服务器和 Python 客户端之间的套接字
【发布时间】:2021-03-31 01:55:06
【问题描述】:

我正在为一个项目开发一个 GUI,该项目返回来自 python 客户端的输出。我想测试 C# 服务器和基本 Python 客户端之间的基本连接,但由于某种原因,每当我运行 Python 时,它都会显示 “ConnectionRefusedError: [WinError 10061] 无法建立连接,因为目标机器主动拒绝了它”。我从过去的经验中知道,这可能与服务器无法正确打开或以某种方式无法连接有关。但是,我无法解决问题所在。我对 C# 很陌生,所以我从互联网上获取了一个服务器代码,只是为了进行一些测试。 我有一个带有简单按钮的主窗口,当我单击它时,我希望它打开套接字连接。 MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ServerOn;

namespace GUI243
{
   public partial class MainWindow : Window
   {
       public MainWindow()
       {
           Server server = new Server();
           InitializeComponent();
       }

       private void Test_Click(object sender, RoutedEventArgs e)
       {
           Server.ExecuteServer();
       }
   }
}

C# 服务器:

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;

namespace ServerOn
{
    class Server
    {
        public static void ExecuteServer()
        {
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHost.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5400);

            Socket listener = new Socket(ipAddress.AddressFamily,
                         SocketType.Stream, ProtocolType.Tcp);
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(5);

                while (true)
                {
                    MessageBox.Show("Waiting connection ... ");
                    Socket clientSocket = listener.Accept();

                    // Data buffer
                    byte[] bytes = new Byte[1024];
                    string data = null;
                    bool flag = false;
                    while (!flag)
                    {

                        int numByte = clientSocket.Receive(bytes);

                        data += Encoding.ASCII.GetString(bytes,
                                                   0, numByte);
                        MessageBox.Show("Text received -> {0} ", data);
                        if (data.Equals("end"))
                        {
                            flag = true;
                        }
                    }
                   // byte[] message = Encoding.ASCII.GetBytes("Test Server");
                   // clientSocket.Send(message);
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                }
            }
            catch (Exception e)
            {
               MessageBox.Show(e.ToString());
            }
        }
    }
} 

Python 客户端:

import socket


def client_program():
    host = socket.gethostname()  # as both code is running on same pc
    port = 5400 # socket server port number

    client_socket = socket.socket()  # instantiate
    client_socket.connect((host, port))  # connect to the server

    message = input(" -> ")  # take input

    while message.lower().strip() != 'end':
        client_socket.send(message.encode())  # send message
        message = input(" -> ")  # again take input
    client_socket.close()  # close the connection


if __name__ == '__main__':
    client_program() 

【问题讨论】:

  • 您正在侦听一个特定 IP,它可能是 IPv6,也许 ::1。考虑监听 IPAddress.Any。
  • 索引零 (ipHost.AddressList[0];) 通常是 IPV6,索引一是 IPV4。此错误还有很多其他原因。最简单的方法是尝试更改索引。

标签: python c# wpf sockets


【解决方案1】:

您应该在您的服务器上接受使用 INADDR_ANY 的连接。 这意味着您接受来自本地计算机上所有 IPv4 地址的连接。 在 C# 中,INADDR_ANY 转换为 IPAddress.Any,即 0.0.0.0。 您还可以使用 TCPListener 使代码更简单。

How to listen on multiple IP addresses?

你得到的错误是没有人在监听端口。由于端口编码正确,IP地址一定是问题。

所以一个小例子是这样的:

class MainClass
{
  public static void Main(string[] args)
  {
    Console.WriteLine("Starting...");
    TcpListener server = new TcpListener(IPAddress.Any, 5400);
    server.Start();
    Console.WriteLine("Started.");
    while (true)
    {
      TcpClient client = server.AcceptTcpClient();
       ... use client to receive
    }
    server.Stop();
  }
}

有关继续使用客户端的代码,请参阅 https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=net-5.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2012-05-18
    • 1970-01-01
    相关资源
    最近更新 更多