ssx
ssx

Reputation: 184

C# client Python server : Connection refused

I'm working on a basic socket communication between C# (client) and Python (server), and I don't understand the reason why I've this error from the client:

[ERROR] FATAL UNHANDLED EXCEPTION: System.Net.Sockets.SocketException: Connection refused at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00159] in /private/tmp/monobuild/build/BUILD/mono-2.10.9/mcs/class/System/System.Net.Sockets/Socket_2_1.cs:1262 at System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint remote_end_point) [0x00000] in /private/tmp/monobuild/build/BUILD/mono-2.10.9/mcs/class/System/System.Net.Sockets/TcpClient.cs:284 at System.Net.Sockets.TcpClient.Connect (System.Net.IPAddress[] ipAddresses, Int32 port) [0x000b3] in /private/tmp/monobuild/build/BUILD/mono-2.10.9/mcs/class/System/System.Net.Sockets/TcpClient.cs:355

My programs are really short and easy so I suppose it's a noob question, but I just don't get it. All I want is a Client sending a message to the server which will print it on the console.

Here is the C# client (the error comes from :socket.Connect("localhost",9999);)

using System;
using System.Net.Sockets;

namespace MyClient
 {
class Client_Socket{
    public void Publish(){
TcpClient socket = new TcpClient();
socket.Connect("localhost",9999);
NetworkStream network = socket.GetStream();
System.IO.StreamWriter streamWriter= new System.IO.StreamWriter(network); 
streamWriter.WriteLine("MESSAGER HARGONIEN");
streamWriter.Flush();   
network.Close();
   }

}
}

And the Python Server:

from socket import *

if __name__ == "__main__":
    while(1):
        PySocket = socket (AF_INET,SOCK_DGRAM)
        PySocket.bind (('localhost',9999))
        Donnee, Client = PySocket.recvfrom (1024)
        print(Donnee)

Thx for your help.

Upvotes: 1

Views: 4572

Answers (1)

icktoofay
icktoofay

Reputation: 129139

You've got two problems. The first is that you're binding to localhost. You probably want to bind to 0.0.0.0 if you want other computers to be able to connect:

PySocket.bind (('0.0.0.0',9999))

The other problem is you're serving with UDP and trying to connect with TCP. If you want to use UDP, you could use UdpClient rather than TcpClient. If you want to use TCP, you'll have to use SOCK_STREAM rather than SOCK_DGRAM and use listen, accept, and recv rather than recvfrom.

Upvotes: 5

Related Questions