C#套接字创建错误

时间:2018-06-24 19:18:37

标签: c# sockets visual-studio-2017 stream-socket-client

因此,我尝试使用C#套接字连接到服务器,但遇到了此错误:

  

System.Net.Internals.SocketExceptionFactory + ExtendedSocketException:   临时性的临时住所   192.168.1.17:9999的自动翻译权

(!!很抱歉,不知道如何将Visual Studio变成英语)

这是我的代码

    Socket sock;

    public MainPage()
    {
        this.InitializeComponent();
        // Initialize MyRecognizer and Load Grammar

        connectToYanaForAll("192.168.1.17", 9999);
        sendInfoToYanaSocket(sock);
        //createGrammarFromYana(sock);
        disconnectFromYana(sock);
    }

    public void sleep(long millis) { Stopwatch stopwatch = Stopwatch.StartNew();  while (true)  { if (stopwatch.ElapsedMilliseconds >= millis) { break; } }  }

    public void connectToYanaForAll(String ip, int port)
    {
        IPAddress ipAddress = IPAddress.Parse(ip); //ipHostInfo.AddressList[0];
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
        // Create a TCP/IP  socket.  
        sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); <-- Fail at this line
        sock.Connect(remoteEP);
    }


    public void disconnectFromYana(Socket sock)
    {
        sock.Shutdown(SocketShutdown.Both);
        sock = null;
    }

    public void sendInfoToYanaSocket(Socket sock)
    {
        String infos = "{\"action\":\"client_infos\",\"type\":\"listen\",\"version\":\"2\",\"location\":\"bureau\",\"token\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}<EOF>";
        byte[] msg = Encoding.ASCII.GetBytes(infos);
        int bytesSent = sock.Send(msg);
        Debug.WriteLine(String.Join(bytesSent.ToString()," bytes sent!"));
    }

    public void createGrammarFromYana(Socket sock)
    {
        String infos = "{\"action\":\"GET_SPEECH_COMMANDS\"}<EOF>";
        byte[] msg = Encoding.ASCII.GetBytes(infos);
        int bytesSent = sock.Send(msg);
        Debug.WriteLine(String.Join(bytesSent.ToString(), " bytes sent!"));

        sleep(200);

        byte[] bytes = new byte[4096];
        int bytesRec = sock.Receive(bytes);
        Debug.WriteLine(String.Join("Received: ", bytesRec.ToString(), " bytes!"));
        Debug.WriteLine("Text = {0}",Encoding.ASCII.GetString(bytes, 0, bytesRec));
    }

我知道您需要使用原始套接字的管理员权限,但是我使用的是stream socket,所以我有点卡住了。 (顺便说一句我正在使用Visual Studio 2017) 我尝试过的:

  • 完全禁用防火墙:不起作用
  • 完全禁用防病​​毒软件:不起作用
  • 要使用TcpClient client = new TcpClient();类:不起作用

3 个答案:

答案 0 :(得分:0)

据Google翻译错误消息说: “尝试访问受其访问权限禁止的套接字,尝试192.168.1.17:9999”

因此,似乎仍然存在权限问题。也许您的系统上运行着只允许某些已知传出连接的防火墙?

答案 1 :(得分:0)

因此解决方案是将该行放入Package.appxmanifest

<Capability Name="privateNetworkClientServer" />

<Capabilities>标记中

答案 2 :(得分:-1)

尝试将套接字绑定到端点而不是连接,然后调用“侦听”。希望对您有帮助