Java Socket客户端无法连接到C#套接字服务器

时间:2016-10-05 09:16:58

标签: java c# sockets

我有一个用例,我必须将数据从.NET应用程序发送到Java应用程序,而我正在尝试使用套接字执行此操作。我有一个使用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);
        }
    }

在Java方面,我创建了一个侦听同一主机和端口的套接字 -

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

我收到以下错误 - java.net.ConnectException:拒绝连接:连接。我使用telnet localhost 13来检查我的服务器是否真的在运行,而且确实如此。因此,我不认为这可能是服务器未运行或防火墙的问题,因为两者都在本地运行。关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:3)

我尝试了你的代码,我遇到了完全相同的问题。您的C#TCP服务器仅绑定到IPv6接口(请检查资源监视器侦听地址)。如果您将服务器更改为new TcpListener(IPAddress.Any, 13),则应该可以正常运行。

相关问题