6

I want to send byte data from Python-Client to C# Server using a simple Socket Application. The C# Server is working fine with a C# Client !

But when I try to use Python Socket to send data to the C#-Server, the data never arrives.

I'm not very used to Python, can someone check my Code and give me a hint how to receive the data in my c# Server?

Did I make a mistake in code? Is this maybe the wrong way to send byte data from Python to C#? Is there a better solution?

Python Client:

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
MESSAGE = b'Hello World !'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
s.close()

C# Server:

private void start()
{
    Console.WriteLine("Port: ");
    _port = Console.ReadLine();
    byte[] buffer = new Byte[1024];
    IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(_port));
    Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(10);

        while (true)
        {
            Console.WriteLine("Waiting for a connection...");
            Socket socket = listener.Accept();
            data = null;

            while (true)
            {
                int bytesRec = socket.Receive(buffer);
                data += Encoding.ASCII.GetString(buffer, 0, bytesRec);
                if (data.IndexOf("<EOF>") > -1)
                {
                    break;
                }
            }

            Console.WriteLine("Text received : {0}", data);
            byte[] msg = Encoding.ASCII.GetBytes(data);

            socket.Send(msg);
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine("\nPress ENTER to continue...");
    Console.Read();
}
5
  • 3
    Your C# code appears to be waiting for "<EOF>" to appear in the received string, but I don't see you sending it in your Python code? You just send "Hello World !" Commented Jul 5, 2018 at 7:13
  • 1
    omg, that's embarrassing... Thank you very much!!! Commented Jul 5, 2018 at 7:15
  • 1
    It happens to the best of us :) Commented Jul 5, 2018 at 7:15
  • Should I delete this post or update my code for future questions? Commented Jul 5, 2018 at 7:16
  • 1
    In this case it's probably better to delete your question in this case since it's not a programming problem really - just a simple oversight. Commented Jul 5, 2018 at 7:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.