簡體   English   中英

Java套接字客戶端無法連接到C#套接字服務器

[英]Java Socket Client Unable to Connect to C# Socket Server

我有一個用例,我必須將數據從.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:連接被拒絕:connect 我已經使用telnet localhost 13來檢查我的服務器是否確實正在運行。 因此,我認為這可能與服務器未運行或防火牆無關,因為兩者均在本地運行。 有關如何解決此問題的任何想法?

我嘗試了您的代碼,但遇到了完全相同的問題。 您的C#TCP服務器僅綁定到IPv6接口(請檢查例如資源監視器偵聽地址)。 如果將服務器更改為new TcpListener(IPAddress.Any, 13)它將正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM