2

我正在做一个示例,其中我试图使用 TCP 将数据从客户端(Windows Phone 8)应用程序传输到 Windows 窗体应用程序(充当服务器)。

在 Windows 窗体应用程序中,我正在创建一个像这样的侦听器

         TcpListener tcpListener = null;

        IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
        try
        {
            // Set the listener on the local IP address
            // and specifing the port.
            tcpListener = new TcpListener(ipAddress, 13);
            tcpListener.Start();
            output = "Waiting for a connection...";
        }
        catch (Exception e)
        {
            output = "Error: " + e.ToString();
            MessageBox.Show(output);
        }

        while (true)
        {

            Thread.Sleep(10);
             TcpClient tcpClient = tcpListener.AcceptTcpClient();

            byte[] bytes = new byte[256];

            NetworkStream stream = tcpClient.GetStream();
            stream.Read(bytes, 0, bytes.Length);
          }

在 windows phone 8 应用程序中,我使用托管套接字连接到侦听器,如下所示

    public Task SendUsingManagedSocketsAsync(string strServerIP)
    {


        // enable asynchronous task completion
        completionSource = new TaskCompletionSource<object>();
        // create a new socket 
        var socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream,
            ProtocolType.Tcp);

        // create endpoint 
        var ipAddress = IPAddress.Parse(strServerIP);
        var endpoint = new IPEndPoint(ipAddress, PORT);

        // create event args 
        var args = new SocketAsyncEventArgs();
        args.RemoteEndPoint = endpoint;
        args.Completed += SocketConnectCompleted;

        // check if the completed event will be raised. If not, invoke the handler manually. 
        if (!socket.ConnectAsync(args))
            SocketConnectCompleted(args.ConnectSocket, args);

        return completionSource.Task;
    }

但是我收到连接被拒绝的套接字错误。我的方法是否正确,如何通过 windows phone 连接 tcp 侦听器。这里我无法更改 windows 窗体应用程序的代码,因为它是我的实时服务器代码。或者是否必须更改我的服务器代码……

4

0 回答 0