0

去年我写了一个家庭自动化应用程序,我可以用它来从笔记本电脑控制服务器——服务器应用程序使用了以下资源

using System.Net;
using System.Net.Sockets;
using System.IO;

然后创建 TCPListener 以接收来自本地网络的命令。

      TcpListener server = new TcpListener(localAddr, port);

      // Start listening for client requests.
      server.Start();

       // Buffer for reading data
       Byte[] bytes = new Byte[256];
       String data = null;

            while (true)
            {

                    TcpClient client = server.AcceptTcpClient();
                     data = null;

                     // Get a stream object for reading and writing
                     NetworkStream stream = client.GetStream();

然后处理流以获得正确的命令和参数,这对客户端和服务器都有效。

我开始为遥控器编写一个地铁应用程序,正因为如此,我不得不使用

using Windows.Networking.Sockets;
using Windows.Networking;

然后创建了一个 async void 来发送命令。(对不起,这很乱)

    async void sendTest()
    {
        StreamSocket socket = new StreamSocket();


        await socket.ConnectAsync(new HostName("192.168.88.1"), "13000",SocketProtectionLevel.PlainSocket);






        DataWriter writer;

        writer = new DataWriter(socket.OutputStream);


        // Write first the length of the string as UINT32 value followed up by the string. Writing data to the writer will just store data in memory. 
        string stringToSend = "Hello";
        writer.WriteUInt32(writer.MeasureString(stringToSend));
        writer.WriteString(stringToSend);

        await writer.StoreAsync();
    }

我得到一个异常(在超时期间没有响应)

我知道我的服务器没有给出响应,但我已经尝试了很多东西,比如 AcceptSocket,但是这些仍然没有检测到客户端已经连接。

我想知道 Metro 是否有另一个我可以使用的网络库,或者是否有人可以为我的服务器侦听器建议替代代码。

提前致谢

4

1 回答 1

3

似乎您正在寻找 StreamSocketListener。那这个呢?

private StreamSocketListener listener;

private async void Test()
{
    listener = new StreamSocketListener();
    listener.ConnectionReceived += OnConnection;
    await listener.BindServiceNameAsync(port.ToString());
}

private async void OnConnection(StreamSocketListener sender,
    StreamSocketListenerConnectionReceivedEventArgs args)
{
    // Streams for reading a writing.
    DataReader reader = new DataReader(listener.InputStream);
    DataWriter writer = new DataWriter(socket.OutputStream);

    writer.WriteString("Hello");
    await writer.StoreAsync();
}
于 2012-09-22T01:09:46.497 回答