Php Client closing when Send request to Supersocket in C# - c#

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.

Related

How to send messages from Cloud to Device with IOT Hub?

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:

NetMQ Polling a rep socket with a timeout in a loop

I'm trying to port my code from an obsolete library called CastleMQ to NetMQ but I'm running into some problems.
I prefer to using polling with a timeout, for reliability - I just found that it worked best for me from trial and error compared to just sitting blocking the port indefinitely.
here is my CastleMQ code
public int ZeroPort;
private void ThreadProc()
{
var ctx = new Context();
try {
using (var repSocket = ctx.CreateSocket(SocketType.Rep))
{
string bindAddress = "tcp://*:"+ZeroPort;
repSocket.Bind(bindAddress);
print2("*** BINDING on {0} ***", bindAddress);
bool quit = false;
while (!quit) {
try {
var polling = new Polling(PollingEvents.RecvReady, repSocket);
polling.RecvReady += (socket) =>
{ // using socket.Recv() here is guaranted to return stuff
var msg = socket.Recv();
var msgStr = Encoding.UTF8.GetString(msg);
print2("[REP:{0}] {1}", bindAddress, msgStr);
switch (msgStr) {
case "positions": {
StringBuilder csv = new StringBuilder();
print2("csv: {0}", csv.ToString());
socket.Send(csv.ToString());
break;
}
default: {
socket.Send("Unrecognized Command: " + msgStr);
break;
}
}
};
polling.Poll(POLL_TIMEOUT_MS); // this returns once some socket event happens
} catch (Exception e) {
if (e is ThreadAbortException) {
quit = true;
print2("\n*** EXITED ***");
} else print2(e.ToString());
}
}
}
} catch (Exception e) {
print2(e.ToString());
} finally {
ctx.Dispose();
}
}
here is what I tried to do and then got lost with NetMQ
private void ThreadProc()
{
try {
string bindAddress = "#tcp://*:" + ZeroPort;
print2("*** BINDING on {0} ***", bindAddress);
using (var repSocket = new ResponseSocket(bindAddress))
using (var poller = new NetMQPoller { repSocket })
{
// bool quit = false;
// while (!quit)
// these event will be raised by the Poller
repSocket.ReceiveReady += (s, a) =>
{
// receive won't block as a message is ready
string msg = a.Socket.ReceiveString(); // defeinition for ReceiveString() can't be found
// send a response
a.Socket.Send("Response"); // it doesn't like "Response", do I need to wrap it in some object?
I'm especially confused as how to add a timeout so I can poll with a timeout in a loop the way my CastleMQ code does.
Any pointers would be much appreciated, thanks

Cannot send midi note out using NAudio and teVirtualMIDI

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!

Can't CREATE an MSMQ Multicast Queue

I swear this code used to work .....
I'm using code from this sample:
https://www.codeproject.com/Articles/871746/Implementing-pub-sub-using-MSMQ-in-minutes
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Messaging;
using System.Threading;
namespace MSMQPublisher
{
class Publisher
{
static void Main(string[] args)
{
try
{
string MSMQMulticastAddress = "FormatName:MULTICAST=234.1.1.1:8001";
var messageQueue = MessageQueue.Create(MSMQMulticastAddress, true);
var stopWatch = new Stopwatch();
stopWatch.Start();
for (var i = 0; i < 10; i++)
{
Message msg = new Message(string.Format($"{DateTime.UtcNow.Ticks}: msg:{i} hello world "));
msg.UseDeadLetterQueue = true;
msg.TimeToBeReceived = new TimeSpan(0, 0, 1, 0);
messageQueue.Send(msg);
Console.WriteLine("[MSMQ] Sent");
Thread.Sleep(10);
}
stopWatch.Stop();
Console.WriteLine("====================================================");
Console.WriteLine("[MSMQ] done sending messages in " + stopWatch.ElapsedMilliseconds);
Console.WriteLine("[MSMQ] Sending reset counter to consumers.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("EXCEPTION: " + ex.Message);
Console.Read();
}
}
}
}
Which throws the exception :
"Cannot create a queue with the path FormatName:MULTICAST=234.1.1.1:8001."} System.Exception
{System.ArgumentException}
I've tried this on several Windows 10 Machines.
I tried setting [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSMQ\Parameters]
"MulticastBindIP"
Can anyone suggest a possible resolution or point out what stupid thing I'm doing?
Thanks

Internet Connection Detector using while loop

I am trying to build a small program that checks for internet connection using while loop, quite new to C#, if possible could you help me figure out the problem with this program thanks.
var client = new WebClient();
while (true)
{
var stream =client.OpenRead("http://www.google.com").ToString();
Console.Write("You are in");
Console.ReadLine();
if (stream == "false")
{
Console.WriteLine("You are out");
break;
}
}
You may just send a Ping as following:
PingReply pingReply = new Ping().Send("http://www.google.com");
if (pingReply != null && pingReply.Status == IPStatus.Success)
{
// Internet is ok
}
This is sample code to check the internet connection. May be this will help you.
public static bool CheckInternetConnection()
{
try
{
using (var client = new WebClient())
{
using (var stream = client.OpenRead("http://www.google.com"))
{
return true;
}
}
}
catch
{
return false;
}
}
From the main call like this:
while (true)
{
if(CheckInternetConnection()==true){
Console.Write("You are in");
}
else{
Console.Write("You are out");
}
}

Categories

Resources