[英]client server programming with windows 10 universal apps
我想創建一個客戶端/服務器系統,其中客戶端是一個收集數據的(C#)Windows 10通用應用程序,而服務器是一個C#程序(某種形式),可以對客戶端進行身份驗證,發送和接收收集到的信息數據等
我已經寫了客戶端通用應用程序的基本內容,現在需要做網絡部分。 誰能提出一個框架和示例,說明如何構建服務器以連接到Windows 10通用應用程序? 我當時正在研究Windows通訊框架,但沒有找到任何有關如何將它們集成到通用應用程序中的示例。
這是我用於應用程序的StreamSocketListener類的服務器端實現的基本示例。 在此示例中,我使用了靜態類。 您還需要客戶端邏輯。
如果需要將數據發送回客戶端,則可以將每個客戶端套接字添加到以IP(或其他某種標識符)為鍵的字典集合中。
希望有幫助!
// Define static class here.
public static StreamSocketListener Listener { get; set; }
// This is the static method used to start listening for connections.
public static async Task<bool> StartServer()
{
Listener = new StreamSocketListener();
// Removes binding first in case it was already bound previously.
Listener.ConnectionReceived -= Listener_ConnectionReceived;
Listener.ConnectionReceived += Listener_ConnectionReceived;
try
{
await Listener.BindServiceNameAsync(ViewModel.Current.Port); // Your port goes here.
return true;
}
catch (Exception ex)
{
Listener.ConnectionReceived -= Listener_ConnectionReceived;
Listener.Dispose();
return false;
}
}
private static async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
var remoteAddress = args.Socket.Information.RemoteAddress.ToString();
var reader = new DataReader(args.Socket.InputStream);
var writer = new DataWriter(args.Socket.OutputStream);
try
{
// Authenticate client here, then handle communication if successful. You'll likely use an infinite loop of reading from the input stream until the socket is disconnected.
}
catch (Exception ex)
{
writer.DetachStream();
reader.DetachStream();
return;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.