如何使用套接字将数据从C#发送到python?

时间:2020-04-01 20:19:20

标签: c# python sockets client client-server

我找不到任何有关如何将数据从C#发送到python的示例或教程。

在我的应用程序中,C#应该继续从硬件读取数据并将其发送到python进行处理。我试图在python上创建基本服务器,并在C#上创建基本客户端,但我始终无法使用C#的以下输出在客户端和服务器之间建立连接无法建立连接,因为目标计算机已主动拒绝它。我在python客户端上测试了我的python服务器,并能够建立连接。

如何使用套接字将数据从C#正确发送到python?我可以按照示例进行教学吗?我的代码有问题吗?在这里:

Python服务器代码:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)

while True:
    clientsocket, address = s.accept()
    print(f"Connection from {address} has been established!")
    clientsocket.send(bytes("Welcome to the server!", "utf-8"))
    clientsocket.close()

C#客户端代码:

 static void ExecuteClient()
        {

            try
            {

                IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddr = ipHost.AddressList[0];
                IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 1234);

                Socket sender = new Socket(ipAddr.AddressFamily,
                           SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    sender.Connect(localEndPoint);

                    Console.WriteLine("Socket connected to -> {0} ",
                                  sender.RemoteEndPoint.ToString());

                    byte[] messageReceived = new byte[1024];

                    int byteRecv = sender.Receive(messageReceived);
                    Console.WriteLine("Message from Server -> {0}",
                          Encoding.ASCII.GetString(messageReceived, 0, byteRecv));

                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }

                // Manage of Socket's Exceptions 
                catch (ArgumentNullException ane)
                {

                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }

                catch (SocketException se)
                {

                    Console.WriteLine("SocketException : {0}", se.ToString());
                }

                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }

            catch (Exception e)
            {

                Console.WriteLine(e.ToString());
            }
        }

1 个答案:

答案 0 :(得分:0)

我知道这个问题很老,但以防万一其他人在互联网搜索中绊倒了。

我刚刚开始学习 Python,我正在用我的 Raspberry Pi(服务器)和 Windows PC(客户端)处理类似的情况。

问题是您正在调用以获取每台机器上的主机名。这显然会有所不同。您的客户端需要连接到服务器的地址。您的客户端代码正在尝试连接到它正在运行的机器,但该连接被拒绝。永远不会联系服务器。

我进行了以下更改并能够建立连接。

Python 服务器代码:

s.bind(("", 1234))

C# 客户端代码:

//IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
//IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("[SERVER IP]"), 1234);

服务器控制台响应:

Connection from ('[CLIENT IP]', 52074) has been established!   

客户端控制台响应:

Socket connected to -> [::ffff:[SERVER IP]]:1234 
Message from Server -> Welcome to the server!
                                                                                    
相关问题