Pratik
Pratik

Reputation: 1138

Java Socket Client Unable to Connect to C# Socket Server

I have a use case, where I have to send data from a .NET application, to a Java application and I'm trying to do this using sockets. I have a server created using C# -

        TcpListener tcpListener = null;
        IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];

        try
        {
            // Set the listener on the local IP address 
            // and specify the port.
            tcpListener = new TcpListener(ipAddress, 13);
            tcpListener.Start();
            Console.WriteLine("The server is running at port 13...");
            Console.WriteLine("The local End point is  -" +
                              tcpListener.LocalEndpoint);
            output = "Waiting for a connection...";
            Console.WriteLine(output);

            Socket s = tcpListener.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
        }
        catch (Exception e)
        {
            output = "Error: " + e.ToString();
            Console.WriteLine(output);
        }
    }

On the Java side, I have created a socket which listens to the same host and port -

Socket socket;
    try {
        socket = new Socket( "localhost", 13);
        System.out.println("Connection established");
        BufferedReader input =
                new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String answer = input.readLine();
        System.out.println(answer);
        socket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

I'm getting the below error - java.net.ConnectException: Connection refused: connect. I have used telnet localhost 13, to check if my server is really running, and it is. So i don't think it could be an issue with server not running or firewalls, since both are running locally. Any ideas on how to resolve this?

Upvotes: 2

Views: 1172

Answers (1)

Nico
Nico

Reputation: 3542

I tried your code and I had exactly the same problem. Your C# TCP Server only binds to the IPv6 interface (check e.g. the resource monitor listening addresses). If you change your server to new TcpListener(IPAddress.Any, 13) it should work.

Upvotes: 4

Related Questions