通过TCP套接字从Windows窗体应用程序发送数据到通用应用程序无法正常工

时间:2016-10-28 07:01:00

标签: c# sockets tcp uwp tcpclient

我将Windows Universal Application作为TCP服务器。所以我想通过TCP套接字发送数据。

如果我从Windows Universal Application作为客户端发送数据,它可以工作。但是我想从Windows Forms Application发送数据而我不能使用StreamSocket,所以我尝试使用客户端发送数据,如下所示:https://msdn.microsoft.com/en-us/library/kb5kfec7(v=vs.110).aspx并且它不起作用。因此,UWP和经典Windows窗体之间的通信是否存在任何限制,因为我尝试了许多不同的选项来使其工作。因此,只有这样才能让它发挥作用,就像我在UWP双方所说的那样。我检查了功能(互联网(客户端),互联网(客户端和服务器),专用网络(客户端和服务器))。

这是TCP服务器的代码:

private readonly int _port;
public int Port { get { return _port; } }

private StreamSocketListener listener;
private DataWriter _writer;

public delegate void DataRecived(string data);
public event DataRecived OnDataRecived;

public delegate void Error(string message);
public event Error OnError;

public SocketServer(int port)
{
    _port = port;
}

public async void Star()
{
    try
    {
        if (listener != null)
        {
            await listener.CancelIOAsync();
            listener.Dispose();
            listener = null;
        }

        listener = new StreamSocketListener();

        listener.ConnectionReceived += Listener_ConnectionReceived;
        await listener.BindServiceNameAsync(Port.ToString());
    }
    catch (Exception e)
    {
        if (OnError != null)
            OnError(e.Message);
    }
}

private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
    var reader = new DataReader(args.Socket.InputStream);
    _writer = new DataWriter(args.Socket.OutputStream);
    try
    {
        while (true)
        {
            uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
            if (sizeFieldCount != sizeof(uint))
                return;                    
            uint stringLenght = reader.ReadUInt32();
            uint actualStringLength = await reader.LoadAsync(stringLenght);
            if (stringLenght != actualStringLength)
                return;
            if (OnDataRecived != null)
            {              
                string data = reader.ReadString(actualStringLength);
                OnDataRecived(data);
            }
        }

    }
    catch (Exception ex)
    {
        if (OnError != null)
            OnError(ex.Message);
    }
}

public async void Send(string message)
{
    if (_writer != null)
    {
        _writer.WriteUInt32(_writer.MeasureString(message));
        _writer.WriteString(message);

        try
        {
            await _writer.StoreAsync();
            await _writer.FlushAsync();
        }
        catch (Exception ex)
        {
            if (OnError != null)
                OnError(ex.Message);
        }
    }
}

有没有人有任何建议? 谢谢你的帮助。

0 个答案:

没有答案