Unity WebSocket4Net - c#

How can I connect a Unity client to a php webserver via WebSocket4Net dll? I
tried an example like that
using WebSocket4Net;
WebSocket websocket = new WebSocket("ws://localhost:2012/");
websocket.Opened += new EventHandler(websocket_Opened);
websocket.Error += new EventHandler<ErrorEventArgs>(websocket_Error);
websocket.Closed += new EventHandler(websocket_Closed);
websocket.MessageReceived += new EventHandler(websocket_MessageReceived);
websocket.Open();
private void websocket_Opened(object sender, EventArgs e)
{
websocket.Send("Hello World!");
}
but got no result

You can check the following links for more information on Unity and web sockets both for the general concept and for the specific to c# implementation.
https://www.youtube.com/watch?v=wfdGw09-rC4
https://www.youtube.com/watch?v=AifcMzEbKnA
https://developer.leapmotion.com/documentation/skeletal/csharp/supplements/Leap_JSON.html
http://docs.unity3d.com/ScriptReference/Network.Connect.html

Related

How to get only one message from MQTT, when messages receiving in C#?

I developed simple IOT device using nodemcu module with 03 sensors. When device is connected, device sent sensor's data to mqtt broker as well. After I getting that data to my .net back end using M2QTT libraries. According to my code, client_MqttMsgPublishReceived method is works as loop. But I need to get that data message, only one time (As I requesting).
I used libraries as:
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
My Code :
private void button2_Click(object sender, EventArgs e)
{
var client = new MqttClient(IPAddress.Parse("172.30.30.21"));
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
var clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
client.Subscribe(new string[] { "topic" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
}
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string result = Encoding.UTF8.GetString(e.Message);
}

C# - Windows Service EventMonitor function with parameters

I'm using PCSC library for SmartCard Readers events detection and trying to use it in Windows service.
Readers search function:
private void CheckPresentReaders()
{
using (var context = new SCardContext())
{
context.Establish(SCardScope.System);
PresentCardReaders = context.GetReaders();
}
}
SmartCard removed function:
private void SCardRemoved(object sender, CardStatusEventArgs e)
{
WriteToLog("Locking machine. SmartCard was removed.");
// LockWorkStation();
}
Monitor creation:
CheckPresentReaders();
if (PresentCardReaders.Length != 0)
{
SCardMonitor monitor = new SCardMonitor(ContextFactory.Instance, SCardScope.System);
monitor.CardRemoved += new CardRemovedEvent(SCardRemoved);
foreach (string reader in PresentCardReaders)
monitor.Start(reader);
}
WriteToLog function is a simple Log Entry creation function.
When it is compiled - service starting and then stopping immediately.
I have two suspects - not delegated WriteToLog and/or SCardRemoved, which requires two parameters -
(object sender, CardStatusEventArgs e)
Those are required by library.
Can this be a problem? Any other suggestions?
Thanks.
I've implemented it properly into Topshelf Service and it does work.
https://github.com/35359595/SmartCardMonitorService

Cannot connect to StreamSocketListener

I'm trying to connect to a StreamSocketListener in my Windows 10 app. This is working if the client socket is inside the same app. But if I try to connect from another application (e.g. Putty) it doesn't work. After a few seconds putty says "Network Error: Connection Refused".
Here is my sample code:
public sealed partial class MainPage : Page
{
private StreamSocketListener listener;
public MainPage()
{
this.InitializeComponent();
listener = new StreamSocketListener();
listener.ConnectionReceived += Listener_ConnectionReceived;
listener.BindServiceNameAsync("12345").AsTask().Wait();
}
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Debug.WriteLine("new connection");
string message = "Hello World!";
using (var dw = new DataWriter(args.Socket.OutputStream))
{
dw.WriteString(message);
await dw.StoreAsync();
dw.DetachStream();
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
// Test connection
var serverHost = new HostName("localhost");
var socket = new StreamSocket();
await socket.ConnectAsync(serverHost, "12345");
using (var dr = new DataReader(socket.InputStream))
{
dr.InputStreamOptions = InputStreamOptions.Partial;
await dr.LoadAsync(12);
var input = dr.ReadString(12);
Debug.WriteLine("received: " + input);
}
}
}
In XAML i added a button to test the client connection.
In the manifest i have checked "Internet (Client)", "Internet (Client & Server)" and "Private Networks (Client & Server)".
EDIT: I'm trying to connect on the same computer. Firewall is deactivated.
You cannot connect to a StreamSocketListener from another app or process running in the same computer, not even with a loopback exemption. You will need to run the client in a different machine.
You can connect to a localhost UWP server app only if you disable the windows firewall (via the control panel) before starting the app, and then quit the firewall service ("net stop MpsSvc", from elevated command prompt) after the app has been started. Loopbackexemption doesn't enable connections to UWP apps, only from UWP apps, in my experience at least...
regards

Windows Phone Offline routing

I am trying to made windows phone application with offline routing. I have found that It is possible by using Bing API.
I have registered and got the key, but I can't find, how can I use the key.
I am using following code:
private async void Button_Click(object sender, RoutedEventArgs e)
{
RouteQuery query = new RouteQuery();
List<GeoCoordinate> wayPoints = new List<GeoCoordinate>();
wayPoints.Add(new GeoCoordinate(47.23449, -121.172447));
wayPoints.Add(new GeoCoordinate(47.062638, -120.691795));
query.Waypoints = wayPoints;
query.QueryCompleted += geoQ_QueryCompleted;
query.QueryAsync();
}
private void geoQ_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
{
try
{
Route myRoute = e.Result;
MessageBox.Show("Completed");
}
catch (TargetInvocationException)
{
/// Unauthorized access exception 0x8004231C
Thread.Sleep(1000); // waiting for completing the query
geoQ_QueryCompleted(sender, e);
}
}
But I am getting Unauthorized access exception 0x8004231C.
I would like to ask you, how can I fix it?
You don't need the key to show offline map. If you have map downloaded on your device, then offline routing should work. You can see the sample to get more details.
Following is the quote from msdn sample,
However, mapping services also work without Internet connectivity when maps are downloaded for offline use.

Sync data between webclient windows phone and webservice

I'm using a webclient on a windows phone 8 app, i have to sync some data with the webservice each minutes (or by pressing a button). I put my webclient in a private data of my object :
private WebClient client_summary;
At the launch of the app the client connects to the webservice :
client_summary = new WebClient();
client_summary.DownloadStringAsync(new Uri("random url" + info_conf.id));
client_sommaire.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadSummaryConf);
I recovered well data, but each time i want to re sync my webclient, data remain the same :(
DispatcherTimer TradeThread = new DispatcherTimer();
TradeThread.Interval = TimeSpan.FromSeconds(10);
TradeThread.Tick += new EventHandler(dispatcherTimer_Tick);
TradeThread.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
pivotMainList.Items.Clear();
summary.Children.Clear();
client_summary.DownloadStringAsync(new Uri("url" + info_conf.id));
}
private void client_DownloadSummaryConf(object sender, DownloadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
e.Result remain the same, whereas if I restart my app the data sync correctly
I don't understand why the sync didn't work ...
Please tell me thanks in advance.
This is a caching issue - the Webclient class (and the HttpClient class if you chose to use that instead) caches server responses. The standard workaround is to append something that varies to your querystring.
For examples see:
How do you disable caching with WebClient and Windows Phone 7
Windows Phone 7 WebRequest caching?

Categories