连接UWP时C#服务器客户端失败

时间:2016-07-14 20:08:41

标签: c# client-server uwp

我尝试在UWP上使用简单的TCP客户端服务器进行通信,我按照此链接UWP socket但看起来它不起作用。我为这两个应用添加了为客户提供的功能。服务器。即使它没有出现在代码中,我也处理了错误,它给了我以下内容:System.Runtime.InteropServices.COMException (0x8007274C): A connection attemps has failed because the connected part has not answer after a certain amount of time or the connection has failed because host has not respond

System.Runtime.InteropServices.COMException (0x8007274C): Une tentative de connexion a échoué car le parti connecté n’a pas répondu convenablement au-delà d’une certaine durée ou une connexion établie a échoué car l’hôte de connexion n’a pas répondu.

据我所知,它在await clientSocket.ConnectAsync(serverHost, serverPort);

行失败了

在学期,它应该在Rasperry Pi 3上运行服务器,在Windows 10移动设备上运行客户端(Lumia 950 XL build 14385),但直到现在我才在运行Windows 10 Pro(构建14385)的表面专业版3上运行

客户端

try
{
        StreamSocket clientSocket;

        clientSocket = new StreamSocket();
        HostName serverHost = new HostName("localhost");
        string serverPort = "5464";
        await clientSocket.ConnectAsync(serverHost, serverPort);
        Stream streamOut = clientSoket.OutputStream.AsStreamForWrite();
        StreamWriter writer = new StreamWriter(streamOut);
        string request = "test";
        await writer.WriteLineAsync(request);
        await writer.FlushAsync();
        Stream streamIn = clientSocket.InputStream.AsStreamForRead();
        StreamReader reader = new StreamReader(streamIn);
        string response = await reader.ReadLineAsync();
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.ToString());//handle
    }

服务器

try
{
    serverSocket = new StreamSocketListener();
    serverSocket.ConnectionReceived += ServerSocket_ConnectionReceived;
    await serverSocket.BindServiceNameAsync("5464");
}
catch(Exception e)
{
    Console.WriteLine(e.ToString());//handle
}

private async void ServerSocket_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
    Stream inputStream = args.Socket.InputStream.AsStreamForRead();
    StreamReader reader = new StreamReader(inputStream);
    string request = await reader.ReadLineAsync();
        Stream outputStream = args.Socket.OutputStream.AsStreamForWrite();
    StreamWriter writter = new StreamWriter(outputStream);
    await writter.WriteLineAsync("Ok");
    await writter.FlushAsync();
}

1 个答案:

答案 0 :(得分:0)

经过一些研究并感谢Stuart Smith,看来两个应用程序之间无法直接连接。出于开发目的,可以在本地计算机上使用工具来启用网络环回。当我试图在我的lumia上运行客户端和我的PC上的服务器时,它运行得很好。

以下是用于理解此内容的链接。

StackOverFlow UWP Enable loopback

Using network loopback in side-loaded Windows Store apps