Socket between C# (With WPF) Server and Python Client

  c++, python, sockets, wpf

I am working on a GUI for a project I have that returns output from a python client . I wanted to test out basic connection between C# Server and a basic Python client but for some reason whenever I run the Python it says "ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it" . I know from past experience that it has to do with probably the server not opening correctly or somehow he cannot connect .But ,I can’t wrap my head around what’s the problem . I’m pretty new to C# so I took a server code from the internet just for some tests .
I have a main window with a simple button and when i click it i want it to open the socket connection.
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# server :

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 Client :

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() 

Source: Python Questions

2 thoughts on - Socket between C# (With WPF) Server and Python Client

  • You are looking at the same server code as I am. You need to change your “host” on the Python client.
    You are currently grabbing the computer name to pass to the C# server socket and it is expecting an IP address.
    For a simple test, manually set “host”…….example; host = ‘127.0.0.1’
    Run your Python client with that test and you should be good to go.
    Now to properly set the host moving forward (assuming the above works for you). you can set the host as such…
    host = socket.gethostbyname(socket.gethostname()) <– This will get the hostname (computername) then it will query for the IP of that computer and set the IP to "host"…
    Hope this solves your issue 🙂

    • Also make an edit to your C# socket server….
      OLD WAY -> IPHostEntry host = Dns.GetHostName()
      NEW WAY -> IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

LEAVE A COMMENT