Hello I was trying to make two programs(server and client) on one machine. I did it with WPF and then I tried to do it with UWP, but I didn't succeed. The problem is that the listener in the server is waiting for a connection, but it never comes. This only happens when I try to do the connection from two separate projects.
If I do it in one project everything works fine. I saw somewhere that it is not possible to run the server and client form one machine with UWP, but the information was not so good explained.
So my question is, is it possible to make two separate projects with UWP for server and client on one computer and if not how can I test the programs(Do I need another computer to test it or there is some other way to do it).
And can someone tell me if there is a possible way to publish my project like the option from Console Applications, so that I can send my client to another computer maybe and try then. All I could find on the internet is how to publish your Apps to the Microsoft Store.
Server
public sealed partial class MainPage : Page
{
string port = "11000";
string hostv4 = "127.0.0.1";
StreamSocketListener server;
public MainPage()
{
InitializeComponent();
StartServer();
}
private async void StartServer()
{
HostName name = new HostName(hostv4);
server = new StreamSocketListener();
server.ConnectionReceived += this.Receive;
await server.BindEndpointAsync(name, port);
Chat.Content += ("server is listening...\n");//chat is a ScrollViewer where I show the received messsges
}
private async void Receive(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
string receivedMsg;
using (var sr = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
{
receivedMsg = await sr.ReadLineAsync();
}
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("server received the request: \"{0}\"\n", receivedMsg)));
}
}
Client
public sealed partial class MainPage : Page
{
string port = "11000";
string hostv4 = "127.0.0.1";
StreamSocket client;
public MainPage()
{
this.InitializeComponent();
Connect();
}
private async void Connect()
{
client = new StreamSocket();
HostName name = new HostName(hostv4);
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client trying to connect...\n")));
await client.ConnectAsync(name, port);
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client connected\n")));
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string request = Input.Text; //Input is the name of my TextBox
using (Stream outputStream = client.OutputStream.AsStreamForWrite())
{
using (var sw = new StreamWriter(outputStream))
{
await sw.WriteLineAsync(request);
await sw.FlushAsync();
}
}
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client sent request: {0}\n", request)));
}
I also have enabled Internet(Client & Server) and Private Networks(Client & Server) from the Capabilities
Related
I have a problem that I lose messages with MQTT although I send them with "QOS_LEVEL_EXACTLY_ONCE".
The loss is only when the receiver is not running and then starts later.
These messages are then not collected.
Version of M2Mqtt is 4.3.0
If both clients, i.e. receiver and transmitter, are running, no messages are lost.
Only if the receiver is not running, the messages are prefetched during this time and do not arrive at the receiver.
I can't find any setting on the server(broker) for how long messages should be saved
sender
public class Programm
{
static MqttClient mqttClient;
static async Task Main(string[] args)
{
var locahlost = true;
var clientName = "Sender 1";
Console.WriteLine($"{clientName} Startet");
var servr = locahlost ? "localhost" : "test.mosquitto.org";
mqttClient = new MqttClient(servr);
mqttClient.Connect(clientName);
Task.Run(() =>
{
if (mqttClient != null && mqttClient.IsConnected)
{
for (int i = 0; i < 100; i++)
{
var Message = $"{clientName} ->Test {i}";
mqttClient.Publish("Application1/NEW_Message", Encoding.UTF8.GetBytes($"{Message}"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
Console.WriteLine(Message);
Thread.Sleep(i * 1000);
}
}
});
Console.WriteLine($"{clientName} End");
}
}
Server
public class Programm
{
static async Task Main(string[] args)
{
Console.WriteLine("Server");
MqttServerOptionsBuilder options = new MqttServerOptionsBuilder()
// set endpoint to localhost
.WithDefaultEndpoint()
// port used will be 707
.WithDefaultEndpointPort(1883);
// handler for new connections
// creates a new mqtt server
IMqttServer mqttServer = new MqttFactory().CreateMqttServer();
// start the server with options
mqttServer.StartAsync(options.Build()).GetAwaiter().GetResult();
// keep application running until user press a key
Console.ReadLine();
}
}
Receiver
public class Programm
{
static MqttClient mqttClient;
static async Task Main(string[] args)
{
var clientName = "Emfänger 1";
var locahlost = true;
Console.WriteLine($"Start of {clientName}");
Task.Run(() =>
{
var servr = locahlost ? "localhost" : "test.mosquitto.org";
mqttClient = new MqttClient(servr);
mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived;
mqttClient.Subscribe(new string[] { "Application1/NEW_Message" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
mqttClient.Connect(clientName);
});
// client.UseConnecedHandler(e=> {Console.WriteLine("Verbunden") });
Console.ReadLine();
Console.WriteLine($"end of {clientName}");
Console.ReadLine();
}
private static void MqttClient_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
{
var message = Encoding.UTF8.GetString(e.Message);
Console.WriteLine(message);
}
}
The default value for the Clean session flag when connecting to the broker with M2MQTT is true.
This means that the broker will discard any queued messages.
https://m2mqtt.wordpress.com/using-mqttclient/
You need to set this to false to ensure the client receives the queued messages.
mqttClient.Connect(clientName, false);
I found the error, saving was missing.
Here is the new code from the server
static async Task Main(string[] args)
{
Console.WriteLine("Server");
MqttServerOptionsBuilder options = new MqttServerOptionsBuilder()
.WithDefaultEndpoint()
.WithDefaultEndpointPort(1883)
.WithConnectionValidator(OnNewConnection)
.WithApplicationMessageInterceptor(OnNewMessage)
.WithClientMessageQueueInterceptor(OnOut)
.WithDefaultCommunicationTimeout(TimeSpan.FromMinutes(5))
.WithMaxPendingMessagesPerClient(10)
.WithPersistentSessions()
.WithStorage(storage);
// creates a new mqtt server
IMqttServer mqttServer = new MqttFactory().CreateMqttServer();
// start the server with options
mqttServer.StartAsync(options.Build()).GetAwaiter().GetResult();
// keep application running until user press a key
Console.ReadLine();
}
I am trying to listen to UDP port 10086, store the data in the string "loggingEvent", combine the string and send it to the UDP port 51999. The UDP client 10086 is used to listen to port 10086 and the Udpclient 10087 is for sending the message to port 51999.
Although I can receive data in the UDP tool "Packet Sender", the C# code failed to listen to the message on port 10086. However, the port "10086", "10087" and "51999" really works, which can be found by using the command "net-stat -ano".
After debugging, I found that the thread exited at the line "var udpResult = await udpClient_listen.ReceiveAsync();", which confused me a lot. I have also tried non-asynchronous and still does not work. However, the "SendAsync" function works well.
In "CharacteristicPage.xaml.cs"
public static string udp_listener_ip;
public static int udp_listener_port;
public static int udp_client_port;
public static string udp_message;
public static UdpClient udpClient_listen;
public static UdpClient udpClient_send;
public static string loggingEvent;
private void button_udp_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
IPEndPoint endPoint_listen= new IPEndPoint(IPAddress.Parse(udp_listener_ip), 10086);
udpClient_listen = new UdpClient(endPoint_listen);
IPEndPoint endPoint1 = new IPEndPoint(IPAddress.Parse(udp_listener_ip), 10087);
udpClient_send = new UdpClient(endPoint1);
UDPListener();
}
private static async Task UDPListener()
{
try
{
while (true)
{
Debug.WriteLine("###############UDP listener task start###############");
var udpResult = await udpClient_listen.ReceiveAsync();
loggingEvent = Encoding.ASCII.GetString(udpResult.Buffer);
Debug.WriteLine("UDP listener received: " + loggingEvent);
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
var messageDialog = new MessageDialog(e.Message, "UDP connect failures");
await messageDialog.ShowAsync();
}
}
In "ObservableGattCharacteristic.cs"
private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
SetValue(args.CharacteristicValue);
});
var udpClient_send = Views.CharacteristicPage.udpClient_send;
var loggingEvent = Views.CharacteristicPage.loggingEvent;
try
{
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(Views.CharacteristicPage.udp_listener_ip), 51999);
DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();
byte[] Payload = Encoding.UTF8.GetBytes(unixTime.ToString() + "," + loggingEvent + "," + ParseValue(value));
await udpClient_send.SendAsync(Payload, Payload.Length, endPoint);
Debug.WriteLine("UDP send message: " + Encoding.UTF8.GetString(Payload));
}
catch
{
Debug.WriteLine("FAILED to publish message!" );
}
}
I'm using 32 feet library to develop Bluetooth communication WPF app, and able to pair the device but not working to connect it and ended up with an exception like below.
Note: I've tried to connect the devices like my mobile and my PC, but both are giving the same errors as explained below.
I've seen somewhere about this issue and they mentioned like, this issue may be because of 32 feet library is not compatible with the Bluetooth device that I've in my PC.
But actually, I've tested this in some other PC's which are running with Windows 7 OS - 64 bit and getting the same error message.
Anyone help me out. Thank you.
Error Message: The requested address is not valid in its context ECD09F51114A:0000110100001000800000805f9b34fb
My code sample:
Guid uId = new Guid("0000110E-0000-1000-8000-00805f9b34fb");
bool receiverStarted = false;
private List<BluetoothDeviceInfo> deviceList;
private List<string> deviceNames;
private BluetoothDeviceInfo deviceInfo;
private string myPin = "1234";
private BluetoothClient sender;
private void BtnScan_Click(object sender, RoutedEventArgs e)
{
ScanAvailableDevices();
}
private void ScanAvailableDevices()
{
lstAvailableDevices.ItemsSource = null;
lstAvailableDevices.Items.Clear();
deviceList.Clear();
deviceNames.Clear();
Thread senderThread = new Thread(new ThreadStart(Scan));
senderThread.Start();
}
private void Scan()
{
UpdateStatus("Starting scan...");
sender = new BluetoothClient();
availableDevices = sender.DiscoverDevicesInRange();
UpdateStatus("Scan completed.");
UpdateStatus(availableDevices.Length.ToString() + " device(s) discovered");
foreach(BluetoothDeviceInfo device in availableDevices)
{
deviceList.Add(device);
deviceNames.Add(device.DeviceName);
}
UpdateAvailableDevices();
}
private void UpdateAvailableDevices()
{
Func<int> devicesDelegate = delegate ()
{
lstAvailableDevices.ItemsSource = deviceNames;
return 0;
};
Dispatcher.BeginInvoke((Action)(() =>
{
devicesDelegate.Invoke();
}));
}
private void PairDevice()
{
deviceInfo = deviceList[lstAvailableDevices.SelectedIndex];
if (CanPair())
{
UpdateStatus("Device paired..");
UpdateStatus("Starting to connect the device");
Thread senderThread = new Thread(new ThreadStart(SenderConnectThread));
senderThread.Start();
}
}
private bool CanPair()
{
if(!deviceInfo.Authenticated)
{
if(!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress,myPin))
{
return false;
}
}
return true;
}
private void LstAvailableDevices_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
deviceInfo = deviceList[lstAvailableDevices.SelectedIndex];
UpdateStatus(deviceInfo.DeviceName + " was selected, attempting connect");
if (CanPair())
{
UpdateStatus("Device paired..");
UpdateStatus("Starting connect thread");
Thread senderThread = new Thread(new ThreadStart(ClientConnectThread));
senderThread.Start();
}
else
{
UpdateStatus("Pair failed");
}
}
private void ClientConnectThread()
{
BluetoothClient sender = new BluetoothClient();
BluetoothAddress address = deviceInfo.DeviceAddress;
//sender.SetPin(deviceInfo.DeviceAddress, myPin);
var endPoint = new BluetoothEndPoint(address, uId);
sender.Connect(endPoint);
//Another way that I've tried
BluetoothClient client = new BluetoothClient();
UpdateStatus("Attempting connect");
//client.Connect(deviceInfo.DeviceAddress, uId);
client.BeginConnect(deviceInfo.DeviceAddress, uId, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient senderE = (BluetoothClient)result.AsyncState;
senderE.EndConnect(result);
Stream stream = senderE.GetStream();
while (true)
{
while (!ready) ;
byte[] message = Encoding.ASCII.GetBytes(txtSenderMessage.Text);
stream.Write(message, 0, message.Length);
}
}
There are libraries in UWP where you can easily make a connection between your desktop and other devices , you can easily handle the Bluetooth Adapter.
There are multiple downloads for 32 feet
Try these
Downloading
https://github.com/inthehand/32feet
Downloads are available here on the Downloads tab. Packages are also available at NuGet:-
InTheHand.Devices.Bluetooth - Modern (v4.x) - Preview NuGet version
32feet.NET - Legacy (v3.x) NuGet version
32feet.NET.Phone - Windows Phone NuGet version
InTheHand.Devices.Enumeration (Windows 8 / Windows Phone Device Pickers) NuGet version
Folks, I'm able to pair and connect it using the same application running in different PC and acting it as a server. Earlier I've tried this without having the same application running in the target PC and thus it's giving the error that I mentioned above.
Thanks guys for your time and support.
I'm trying to make datagramsocket on UWP connect to UDPClient on desktop.
The odd thing is that datagramsocket never receive any message from UDPClient(event not work) unless send out message to UDPClient from datagramsocket first.
On the other hand, i'm sure my config(IP/PORT setting) is OK, because same config on UDPClients works OK.
Is there anything wrong with my code?(UWP CODE:)
private async void btn_start_Click(object sender, RoutedEventArgs e)//Listen
{
hostname = new HostName("192.168.1.5");
remotename = new HostName("192.168.1.5");
datagramsocket = new DatagramSocket();
datagramsocket.MessageReceived += Datagramsocket_MessageReceived;
try
{
await datagramsocket.BindServiceNameAsync("8010");
await datagramsocket.ConnectAsync(remotename, "8009");
}
catch(Exception err)
{
//show err message method
}
}
private async void Datagramsocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{//read from args
//it works after click send button
}
//if i don't click btn_send first, then the MessageReceived event will never work
private async void btn_send_Click(object sender, RoutedEventArgs e)//send
{
string str_send = tb_send.Text;
byte[] str_byte = Encoding.Unicode.GetBytes(str_send);
IOutputStream outputstream = await datagramsocket.GetOutputStreamAsync(remotename, "8009");
DataWriter writer = new DataWriter(outputstream);
writer.WriteBytes(str_byte);
await writer.StoreAsync();
}
Afternoon all,
I have a windows service which subscribes to an Office365 email account and awaits new emails, when they arrive it processes their attachments, and all is well with the world.
But... for some reason, the applications stops receiving notifications after an undetermined amount of time.
I have handled the 'OnDisconnect' event and reestablish a connection as shown in the below code, but that doesnt seem to be fixing this issue. The windows service continues to run fine, and if I restart the service everything is good again, until is failed again.
This is the my class for running exchange:
public class ExchangeConnection
{
static readonly ExchangeService Service = Exchange.Service.ConnectToService(UserDataFromConsole.GetUserData(), new TraceListener());
public event EmailReceivedHandler OnEmailReceived;
public ExchangeConnection()
{
}
public void Open()
{
SetStreamingNotifications(Service);
var signal = new AutoResetEvent(false);
signal.WaitOne();
}
private void SetStreamingNotifications(ExchangeService service)
{
var streamingsubscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail);
var connection = new StreamingSubscriptionConnection(service, 30);
connection.AddSubscription(streamingsubscription);
connection.OnNotificationEvent += OnEvent;
connection.OnSubscriptionError += OnError;
connection.OnDisconnect += OnDisconnect;
connection.Open();
}
public void MoveEmail(ItemId id, String folderName = "Archived Emails")
{
var rootFolder = Folder.Bind(Service, WellKnownFolderName.Inbox);
var archivedFolder = rootFolder.FindFolders(new FolderView(100)).FirstOrDefault(x => x.DisplayName == folderName);
if (archivedFolder == null)
{
archivedFolder = new Folder(Service) { DisplayName = folderName };
archivedFolder.Save(WellKnownFolderName.Inbox);
}
Service.MoveItems(new List<ItemId> {id}, archivedFolder.Id);
}
#region events
private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
//The connection is disconnected every 30minutes, and we are unable to override this,
//so when we get disconnected we just need to reconnect again.
var connection = (StreamingSubscriptionConnection)sender;
connection.Open();
}
private void OnEvent(object sender, NotificationEventArgs args)
{
var subscription = args.Subscription;
// Loop through all item-related events.
foreach (var notification in args.Events)
{
switch (notification.EventType)
{
case EventType.NewMail:
if (notification is ItemEvent)
{
var email = Item.Bind(Service, new ItemId(((ItemEvent) notification).ItemId.UniqueId));
OnEmailReceived(new EmailReceivedArgs((EmailMessage)email));
}
break;
}
}
}
private void OnError(object sender, SubscriptionErrorEventArgs args)
{
var e = args.Exception;
Logger.LogException(e,LogEventType.Error);
}
#endregion events
}
Any help would be great, thanks.
EDIT:
After improving the error logging I have found this exception occuring:
Exception: The specified subscription was not found.
Any ideas what is causing this?
With Office365 you need to make sure you deal with affinity see http://msdn.microsoft.com/en-us/library/office/dn458789(v=exchg.150).aspx . Adding those headers will ensure your requests will always routed to the correct servers.
Cheers
Glen