I have tried to receive cloud to device message through IOT Hub using the steps mentioned in the link below:
https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-c2d
I have attached the code that I am using and the result I am getting.
In the simulated device app, I am calling this method "ReceiveMessageAsync()".
I have updated the screenshot of the output that I am getting.
After entering the "Enter", I am not getting any output.
After decoding the code, I could see that in the ReceiveMessageAsync() method, I am getting receivedMessage == null.
Please help me with this code and suggest the changes that I should make to make it work perfectly.
=======================================
public async void ReceiveMessageAsync()
{
try
{
Message receivedMessage = await _deviceClient?.ReceiveAsync();
if(receivedMessage == null)
{
ReceivedMessage = null;
return;
}
ReceivedMessage = Encoding.ASCII.GetString(receivedMessage.GetBytes());
if(double.TryParse(ReceivedMessage, out var requestedNoise))
{
ReceivedNoiseSetting = requestedNoise;
}
else
{
ReceivedNoiseSetting = null;
}
await _DeviceClient?.CompleteAsync(receivedMessage);
}
catch (NullReferenceException ex)
{
System.Diagnostics.Debug.WriteLine("The DeviceClient is null.");
}
}
==================================================
using System;
using Ststem.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices;
using System.Linq;
namespace SendCloudToDevice
{
internal class Program
{
static ServiceClient serviceClient;
static string connectionString = "<connectionString>";
static string targetDevice = "<deviceID>";
public static async Task Main(String[] args)
{
console.WriteLine("Send Cloud to device Message");
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
ReceiveFeedbackAsync();
Console.WriteLine("Press any key to send C2D mesage.");
Console.ReadLine();
sendCloudToDeviceMessageAsync().Wait();
Console.ReadLine();
}
private async static Task SendCloudToDeviceMessageAsync()
{
var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message."));
commandMessage.Ack = DeliveryAcknowledgement.Full;
await serviceClient.sendAsync(targetDevice,commandMessage);
}
private async static void ReceiveFeedbackAsync()
{
var feedbackReceiver = serviceClient.GetFeedbackReceiver();
Console.WriteLine("\n Receiving c2d feedback from service");
while (true)
{
var feedbackBatch = await feedbackReceiver.ReceiveAsync();
if(feedbackBatch == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received feedback: {0}",string.Join(", ", feedbackBatch.Recorfds.Select(f => f.StatusCode)));
Console.ResetColor();
await feedbackReceiver.CompleteAsync(feedbackBatch);
}
}
}
}
[1]: https://i.stack.imgur.com/sS8N0.jpg![enter image description here](https://i.stack.imgur.com/THylN.jpg)
If you just want to send messages to a device and get messages from a device, try the code below:
using System;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices;
using System.Linq;
using System.Text;
namespace SendCloudToDevice
{
internal class Program
{
public static void Main(String[] args)
{
var deviceConnStr = "";
var serviceClientStr = "";
//sned a new message from could to device
var serviceClient = ServiceClient.CreateFromConnectionString(serviceClientStr);
var messageContent = "Hello! This is a message from Cloud!";
var commandMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(messageContent));
serviceClient.SendAsync("<deviceID here>", commandMessage).GetAwaiter().GetResult();
Console.WriteLine("sent message to device,content : "+ messageContent);
//device receive messages from cloud
var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr);
Console.WriteLine("\nReceiving cloud to device messages from service");
while (true)
{
var receivedMessage = deviceClient.ReceiveAsync().GetAwaiter().GetResult();
if (receivedMessage == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received message: {0}",
Encoding.ASCII.GetString(receivedMessage.GetBytes()));
Console.ResetColor();
deviceClient.CompleteAsync(receivedMessage).GetAwaiter().GetResult();
}
}
}
}
Result:
You can also send messages from Portal:
Related
I try to implement the HoloLens2 - PC TCP Socket.
For the Unity project, which is built into HoloLens2, I have selected the InternetClient, InternetClientServer, and PrivateNetworkClientServer options.
And I also closed the SSL connection required option for HoloLens2.
The result is that HoloLens2 can create a socket successfully, but I run the code on a PC to connect the HoloLens2 socket server always shows timeout.
The code is below.
How can I solve...?
HoloLens 2: TCP Server
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
#if !UNITY_EDITOR
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
#endif
//Able to act as a reciever
public class UniversalSampleTutorial : MonoBehaviour
{
public String _input = "Waiting";
public bool _listening = false;
public bool _connect = false;
#if !UNITY_EDITOR
StreamSocket socket;
StreamSocketListener listener;
String port;
String message;
#endif
// Use this for initialization
void Start()
{
#if !UNITY_EDITOR
listener = new StreamSocketListener();
port = "9090";
listener.ConnectionReceived += Listener_ConnectionReceived;
listener.Control.KeepAlive = true;
Listener_Start();
#endif
}
#if !UNITY_EDITOR
private async void Listener_Start()
{
Debug.Log("Listener started");
try
{
await listener.BindServiceNameAsync(port);
}
catch (Exception e)
{
Debug.Log("Error: " + e.Message);
}
Debug.Log("Listening");
_listening = true;
}
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Debug.Log("Connection received");
_connect = true;
try
{
while (true) {
using (var dw = new DataWriter(args.Socket.OutputStream))
{
dw.WriteString("Hello There");
await dw.StoreAsync();
dw.DetachStream();
}
using (var dr = new DataReader(args.Socket.InputStream))
{
dr.InputStreamOptions = InputStreamOptions.Partial;
await dr.LoadAsync(12);
var input = dr.ReadString(12);
Debug.Log("received: " + input);
_input = input;
}
}
}
catch (Exception e)
{
Debug.Log("disconnected!!!!!!!! " + e);
}
}
#endif
void Update()
{
if (_listening == false && _connect == false)
this.GetComponent<TextMesh>().text = _input;
else if (_listening == true && _connect == false)
this.GetComponent<TextMesh>().text = "Listening";
else if (_listening == true && _connect == true)
this.GetComponent<TextMesh>().text = "Connect";
}
}
PC: TCP Client
import asyncio
#THIS CODE WORKS SENDING STRING MESSAGE TO HOLOLENS
async def tcp_echo_client(message, loop):
reader, writer = await asyncio.open_connection('192.168.0.102', 9090, loop=loop)
print('Send: %r' % message)
writer.write(message.encode())
data = await reader.read(100)
print('Received: %r' % data.decode())
print('Close the socket')
writer.close()
message = 'hello there frend'
loop = asyncio.get_event_loop()
loop.run_until_complete(tcp_echo_client(message, loop))
loop.close()
AF_UNIX sockets are supported on Windows starting in Windows Insider build 17093 (Windows 10 version 1803).
See Windows/WSL Interop with AF_UNIX blog post on the Windows Command Line blog.
There is any way to use it to Windows/WSL interop with two .NET Core app (client and server)
Thank you
You need the UnixDomainSocketEndPoint class.
Also note that this only works on WSL version 1 and not version 2.
Here's a quick working sample I just cobbled together. Note that there's no real error-handling or robust input validation.
You'll need to either supply a path at the command line, create a c:\tmp\wsl directory, or edit the paths in the code.
using System;
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
namespace AFUnixTest
{
class Program
{
static UnixDomainSocketEndPoint _endpoint;
static Socket UnixSocket => new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
static string _socketPath;
static byte[] _buffer = new byte[1024];
static void Main(string[] args)
{
_socketPath = IsLinux ? "/mnt/c/tmp/wsl/unix.sock" : "c:\\tmp\\wsl\\unix.sock";
if (args.Length == 0)
{
Usage();
return;
}
if (args.Length > 1) _socketPath = args[1];
_endpoint = new UnixDomainSocketEndPoint(_socketPath);
if (args[0].ToLower() == "-s")
{
Server();
}
else if (args[0].ToLower() == "-c")
{
Client();
}
else
{
Usage();
}
}
static void Usage()
{
Console.WriteLine("Usage:");
Console.WriteLine($" { AppDomain.CurrentDomain.FriendlyName } -s or -c [socket path]");
Console.WriteLine($" Socket path should be in { (IsLinux ? "Linux" : "Windows") } path format.");
}
static void Server()
{
if (File.Exists(_socketPath)) File.Delete(_socketPath);
Console.WriteLine("Waiting...");
using (Socket listener = UnixSocket)
{
listener.Bind(_endpoint);
listener.Listen(10);
using (Socket handler = listener.Accept())
{
while (true)
{
int bytesReceived = handler.Receive(_buffer);
string message = Encoding.ASCII.GetString(_buffer, 0, bytesReceived);
if (message.ToLower().StartsWith("exit")) break;
Console.WriteLine($"Received [{ message }].");
}
Console.WriteLine("Exit received. Exiting...");
handler.Shutdown(SocketShutdown.Both);
}
}
}
static void Client()
{
Console.WriteLine("Starting client. Enter text. \"Exit\" (without quotes) to quit.");
using (Socket sender = UnixSocket)
{
sender.Connect(_endpoint);
while (true)
{
string message = Console.ReadLine();
var output = Encoding.ASCII.GetBytes(message);
int bytesSent = sender.Send(output);
Console.WriteLine($"Sent [{ bytesSent }] bytes.");
if (message.ToLower().StartsWith("exit")) break;
}
sender.Shutdown(SocketShutdown.Both);
}
}
}
}
I am using nodejs, msmq and .net as technology stack in my project. I am collecting data from hardware using nodejs script and writing into MSMQ.
I want to read this MSMQ in .net but I am getting below error.
In addition I am not able to receive the message as well.
Error
System.Xml.XmlException: Data at the root level is invalid. Line 1, position
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
'objMessage.ConnectorType' threw an exception of type
'System.InvalidOperationException'
'objMessage.Body' threw an exception of type 'System.Xml.XmlException'
//Nodejs script
const msmq = require('updated-node-msmq');
const queue = msmq.openOrCreateQueue('.\\Private$\\EEG');
queue.send(records);
// C# code
if (MessageQueue.Exists(#".\Private$\EEG")){
objMessageQueue = new MessageQueue(#".\Private$\EEG");
}
objMessage = objMessageQueue.Receive();
objMessage.Formatter = new XmlMessageFormatter(new Type[]
{typeof(Payload) });
var message = (Payload)objMessage.Body;
I am able to solve the issue. Instead of using message.Body I have used message.BodyStream and converted that data into binary format. here's my solution.
using System;
using System.Messaging;
using System.Data.SqlClient;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using System.Text;
namespace NeuroskyListener
{
class Program
{
public static bool isRunning;
private static MessageQueue messageQueue;
public static void Main(string[] args)
{
InitializeQueue();
Console.ReadLine();
}
private static void InitializeQueue()
{
string queuePath = #".\Private$\eegNew";
if (!MessageQueue.Exists(queuePath))
{
messageQueue = MessageQueue.Create(queuePath);
}
else
{
messageQueue = new MessageQueue(queuePath);
}
isRunning = true;
messageQueue.Formatter = new XmlMessageFormatter(new Type[] {typeof(string) });
messageQueue.ReceiveCompleted += OnReceiveCompleted;
messageQueue.BeginReceive();
}
private static void OnReceiveCompleted(object source, ReceiveCompletedEventArgs asyncResult)
{
try
{
MessageQueue mq = (MessageQueue)source;
if (mq != null)
{
try
{
System.Messaging.Message message = null;
try
{
message = mq.EndReceive(asyncResult.AsyncResult);
BinaryReader reader = new BinaryReader(message.BodyStream);
int count = (int)message.BodyStream.Length;
byte[] bytes = reader.ReadBytes(count);
string bodyString = Encoding.UTF8.GetString(bytes);
eegPayload lst = JsonConvert.DeserializeObject<eegPayload>(bodyString);
}
catch (Exception ex)
{
// LogMessage(ex.Message);
}
if (message != null)
{
//Payload payload = message.Body as Payload;
Console.WriteLine(message.Body);
//if (payload != null)
//{
// receivedCounter++;
// if ((receivedCounter % 10000) == 0)
// {
// string messageText = string.Format("Received {0} messages", receivedCounter);
// LogMessage(messageText);
// }
//}
}
}
finally
{
if (isRunning)
{
mq.BeginReceive();
}
}
}
return;
}
catch (Exception exc)
{
//LogMessage(exc.Message);
}
}
}
}
I am trying to send a Midi Note On message out to DAW software using NAudio, with a virtual port created by teVirtualMIDI. I am able to see the "device" created by teVirtualMIDI in Ableton Live 10, but have been unsuccessful in receiving any information in Live. My sound is turned up, and I never see Live's Midi meter move. The Code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NAudio.Midi;
using TobiasErichsen.teVirtualMIDI;
namespace BDBConsole_1_0
{
public class BDBMidiClient
{
public static ConsoleKeyInfo cKi;
public static TeVirtualMIDI port;
static MidiOut midiOut;
int midiOutIndex;
//public static List<MidiEvent> noteEvent;
static void Main(string[] args)
{
CreateMidiPort();
}
public static void CreateMidiPort()
{
TeVirtualMIDI.logging(TeVirtualMIDI.TE_VM_LOGGING_MISC | TeVirtualMIDI.TE_VM_LOGGING_RX | TeVirtualMIDI.TE_VM_LOGGING_TX);
string portName = "BDB Client";
//port = new TeVirtualMIDI(portName, 65535, TeVirtualMIDI.TE_VM_FLAGS_INSTANTIATE_BOTH);
port = new TeVirtualMIDI(portName);
Console.WriteLine("New Midi Port Opened...");
Console.ReadKey();
EnumerateMidiOutDevices();
Thread thread = new Thread(new ThreadStart(SendNextMidiOutMessage));
thread.Start();
//SendNextMidiOutMessage();
}
public static void EnumerateMidiOutDevices()
{
int noOutDevices = MidiOut.NumberOfDevices;
Console.WriteLine("No. of Midi Out Devices..." + noOutDevices);
Console.ReadKey();
string deviceOutOne = MidiOut.DeviceInfo(1).ProductName;
Console.WriteLine("Device One..." + deviceOutOne);
Console.ReadKey();
}
public static void SendNextMidiOutMessage()
{
midiOut = new MidiOut(deviceNo: 0);
//events = new List<MidiEvent>();
int channel = 1;
int note = 64;
var noteOnEvent = new NoteOnEvent(0, channel, note, 127, 1000);
try
{
//while (true) loop here before
do
{
Console.WriteLine("Send Midi Note...");
cKi = Console.ReadKey();
midiOut.Send(noteOnEvent.GetAsShortMessage());
Console.WriteLine("Note Sent...");
cKi = Console.ReadKey();
} while (cKi.Key != ConsoleKey.Escape);
port.shutdown();
Console.WriteLine("Midi Port Closed...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("thread aborting: " + ex.Message);
}
}
}
}
Any Help with this would be greatly appreciated!
I have server in c#, client in PHP. I used Supersocket[https://supersocket.codeplex.com/] to communication between client and server.
C# with Supersocket - Serverside
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase;
using SuperSocket.Common;
using SuperSocket.SocketEngine;
using SuperSocket;
using System.Configuration;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press any key to start the WebSocketServer!");
Console.ReadKey();
Console.WriteLine();
var appServer = new AppServer();
//Setup the appServer
if (!appServer.Setup(2020))
{
Console.WriteLine("Failed to setup!");
Console.ReadKey();
return;
}
appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);
appServer.NewRequestReceived += new RequestHandler<AppSession, SuperSocket.SocketBase.Protocol.StringRequestInfo>(appServer_NewRequestReceived);
appServer.SessionClosed += new SessionHandler<AppSession, CloseReason>(appServer_SessionClosed);
Console.WriteLine();
//Try to start the appServer
if (!appServer.Start())
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
}
Console.WriteLine("The server started successfully, press key 'q' to stop it!");
while (Console.ReadKey().KeyChar != 'q')
{
Console.WriteLine();
continue;
}
//Stop the appServer
appServer.Stop();
Console.WriteLine();
Console.WriteLine("The server was stopped!");
Console.ReadKey();
}
static void appServer_NewSessionConnected(AppSession session)
{
session.Send("Swelcome");
}
static void appServer_SessionClosed(AppSession session, CloseReason value)
{
session.Send("Server: " + "welcome");
}
static void appServer_NewRequestReceived(AppSession session, SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)
{
try
{
switch (requestInfo.Key.ToUpper())
{
case ("ECHO"):
session.Send(requestInfo.Body);
break;
case ("ADD"):
session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
break;
case ("MULT"):
var result = 1;
foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))
{
result *= factor;
}
session.Send(result.ToString());
break;
default:
Console.WriteLine("Default");
session.Send(requestInfo.Body);
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
PHP Code - Client side
class XoneDataReciver
{
var $socketPtr;
function OpenConnection($server, $port)
{
$this->socketPtr = fsockopen($server, $port, $errno, $errstr, 0.4);
if (!$this->socketPtr) {
echo "Network down. Please refresh the page again or try again later."; exit();
} else {
return 0;
}
}
function MakeRequest($action, $params = array())
{
if (!$this->socketPtr)
return "error";
$this->sendRequest($action); //Error - Client closing
return $this->readAnswer(); // Got msg from server
}
function sendRequest($request)
{
fputs($this->socketPtr, $request);
}
}
$xone_ip ="127.0.0.1";
$xone_port = "2020";
$xonerequest = new XoneDataReciver;
$xonerequest->OpenConnection($xone_ip, $xone_port);
?>
I got msg from server to client(PHP). But when I try to send msg from php to c#, SessionClosed event fire and the error shows "Client closing". Anyone help me to communicate php client to c# server via Supersocket. Thanks in advance.
Increasing the MaxConnectionNumber in server configuration worked for me.