.net remoting, How to reconnect if the connect is lost? - c#

I have this working but i don't understand how to predict when the connection has dropped and needs to reconnect to the server.
what i want to do is have the client connect right away to the .net remoting server if it drops out, sort of like keep trying to connect and disregard if it does not need to.
help appreciated.
here is my code:
namespace TaskClient
{
using System;
using System.Reflection;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Threading;
using TaskShared;
class Program
{
static void Main(string[] args)
{
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan, false);
Connections remObject = (Connections)Activator.GetObject(typeof(Connections), "tcp://localhost:8085/TaskServer");
if (remObject == null)
{
Console.WriteLine("Could not connect to TaskServer. (tcp://localhost:8085/TaskServer)");
}
else
{
Console.WriteLine("Connected to Task Server.");
var rt = new TestTask()
{
ApplicationName = Assembly.GetExecutingAssembly().FullName,
ComputerName = Environment.MachineName,
VersionInfo = "1.0.0",
JobRunning = "None"
};
remObject.Add(rt);
}
while (true)
{
//TODO:
//Check if connected.. how?
//Re-create the connection... how?
//doing this simple won't work:
if (remObject == null)
remObject = (Connections)Activator.GetObject(typeof(Connections), "tcp://localhost:8085/TaskServer");
remObject.Invalidate(remObject[rt]);
Thread.Sleep(1000);
}
}
}
}

Related

lavalink not working when making discord bot with DSharpPlus. not throwing any errors

command class, no errors when running
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Lavalink;
namespace MusicBot
{
public class MediaCommands : BaseCommandModule
{
[Command("join"), Description("joins user voice channel")]
public async Task JoinVC(CommandContext ctx, DiscordChannel chn)
{
var lava = ctx.Client.GetLavalink();
if (!lava.ConnectedNodes.Any())
{
await ctx.RespondAsync("The Lavalink connection is not established");
return;
}
var node = lava.ConnectedNodes.Values.First();
if (chn.Type != ChannelType.Voice)
{
await ctx.RespondAsync("Not a valid voice channel");
return;
}
await node.ConnectAsync(chn);
await ctx.RespondAsync($"Joined {chn}");
}
program class no error when running
using System;
using DSharpPlus;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using DSharpPlus.CommandsNext;
using DSharpPlus.Lavalink;
using DSharpPlus.Net;
using LortBasic;
using LortMusic;
namespace Lort
{
class Program
{
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
var LortBot = new DiscordClient(new DiscordConfiguration()
{
Token = "mytoken",
TokenType = TokenType.Bot,
Intents = DiscordIntents.All,
MinimumLogLevel = LogLevel.Debug
});
//lavalink
var endpoint = new ConnectionEndpoint
{
Hostname = "127.0.0.1",
Port = 25565
};
var lavalinkconfig = new LavalinkConfiguration
{
Password = "youshallnotpass",
RestEndpoint = endpoint,
SocketEndpoint = endpoint,
};
var lavalink = LortBot.UseLavalink();
await LortBot.ConnectAsync();
await lavalink.ConnectAsync(lavalinkconfig);
await Task.Delay(-1);
I'm following this guide to make a discord bot with c# using DSharpPlus https://dsharpplus.github.io/articles/audio/lavalink/setup.html and everything works up until trying to get the bot to join a voice channel. it has admin rights and no errors in lavalink console, bot console, vs, none anywhere. nothing happens though... at all

Can not find BLE device using 32feet.NET

I use VS 2017 in windows 7 to write a hci tool for searching the BLE device.
I use bluetooth CSR 4.0 dongle(the driver is installed and works well) and BlueSoleil.
But when after the BLE device's advertising, the program can not find it. I have tried to use other app like lightblue for searching, the BLE device is findable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd)
{
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd +
"'");
}
if (args.Length < 2)
{
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
var dev = new BluetoothDeviceInfo(_searchAddress);
bool isInRange = GetCanConnectTo(dev);
if (isInRange)
{
PrintDevice(dev);
}
else
{
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
When I run the program using:“hcitool.exe name 123456654321(the BLE address)” , it shows: can't see that device.
The return value of GetCanConnectTo() is false so it shows: can't see that device.
I do not know how I could connect to the ble device using my code.

Akka.NET Cluster Client

I try to create application using Akka.NET.
The main goal is to make a server that can handle many client connections and requests at the same time. I chose Akka.NET for this. I have a cluster, which now consists only 1 node.
I also have cluster clients (ClusterClient) that are simultaneously starting to connect to the server. The logic of the client is simple: it connects to the server and subscribe an actor there. There are no problems with publish yet, customers are getting everything, of course, if the connection is stable. Somewhere near ​​~4000-5000 client connections, reconnects begin and the connection is lost accordingly. I have tried to add a second node to the cluster and make 3000 connections for each node, but this was unsuccessful.
The question is how to make a server on AKKA.Net, which would hold a large number of connections (for example, 100 000 - 1 000 000). And could I use cluster for this purpose?
Server
using Akka.Actor;
using Akka.Configuration;
using System;
using System.Configuration;
using Akka.Cluster.Tools.Client;
using System.Threading;
namespace CoreSPServer
{
class Program
{
static void Main(string[] args)
{
Config config = ConfigurationFactory.ParseString(ConfigurationManager.AppSettings["ClusterConfig"]);
ActorSystem system = ActorSystem.Create("ClusterSystem", config);
var publisher = system.ActorOf(Props.Create(() => new Publisher()), "Publisher");
var clientSub = system.ActorOf(Props.Create(() => new ClientSubscriber()), "Sub");
ClusterClientReceptionist.Get(system).RegisterService(clientSub);
if (Console.ReadLine() == "start")
{
publisher.Tell("test");
Thread.Sleep(10);
}
Console.ReadKey();
}
}
}
ClientSubscriber and publisher
class ClientSubscriber : ReceiveActor
{
public ClientSubscriber()
{
var mediator = DistributedPubSub.Get(Context.System).Mediator;
Receive<IActorRef>(senderToSub =>
{
mediator.Tell(new Subscribe("content", senderToSub));
});
}
}
public class Publisher : ReceiveActor
{
public Publisher()
{
var mediator = DistributedPubSub.Get(Context.System).Mediator;
Receive<string>(str =>
{
var upperCase = str.ToUpper();
mediator.Tell(new Publish("content", upperCase));
});
}
}
Client
static void Main(string[] args)
{
var config = ConfigurationFactory.ParseString(ConfigurationManager.AppSettings["ClientConf"]);
ActorSystem Sys = ActorSystem.Create("ClusterClient", config);
//Connection path to Cluster Node
var initialContacts = new List<ActorPath>(){
ActorPath.Parse("akka.tcp://ClusterSystem#localhost:5001/system/receptionist"),
}.ToImmutableHashSet();
var settings = ClusterClientSettings.Create(Sys).WithInitialContacts(initialContacts);
for(int i = 0; i < 5000; i++)
{
IActorRef c = Sys.ActorOf(ClusterClient.Props(settings), "client" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
var asd = Sys.ActorOf(Props.Create<Subscriber>(), "clientSub" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
c.Tell(new ClusterClient.Send("/user/Sub5001", asd));
Thread.Sleep(1/10);
}
Console.ReadKey();
}
Server config
akka {
extensions = ["Akka.Cluster.Tools.Client.ClusterClientReceptionistExtensionProvider, Akka.Cluster.Tools"]
actor.provider = cluster
remote {
dot-netty.tcp {
port = 5001
public-hostname = localhost
auto-down-unreachable-after = off
}
}
cluster {
seed-nodes = ["akka.tcp://ClusterSystem#localhost:5001"]
}
}

Ping a website and save the data in an .csv file

When the code is RUN it has to ping the websites I specify 4 times each and then write the results in a .csv file. But I'm keep getting a TIMEOUT error. Can anyone tell me why? I tried so many different things and noting is working so far. Please help me out.
static void Main(string[] args)
{
List<string> lstWebSites = new List<string>();
lstWebSites.Add("www.yahoo.com");
lstWebSites.Add("www.att.com");
lstWebSites.Add("www.verizon");
string filename = #"PingLog.csv";
{
using (var writer = new StreamWriter(filename, true))
{
foreach(string website in lstWebSites)
{
writer.WriteLine(website);
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(website, 1000);
if (reply != null)
{
Console.WriteLine("{0}, {1}", reply.Address, reply.RoundtripTime);
}
}
catch
{
Console.WriteLine.("ERROR: You have some TIMEOUT issue");
}
}
}
}
}
}
}
Here's a working example. I added some comments where you had syntax errors or where I made adjustments to your original code.
// Missing quotes, should probably be a full file path
string filename = #"C:\temp\PingLog.csv";
// You had an extra opening brace here
// Open a file for writing using the filename, and a flag that means whether to append
using (var writer = new StreamWriter(filename, false))
{
// Write a CSV header
writer.WriteLine("Status, Time, Address");
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send("www.yahoo.com", 1000);
if (reply != null)
{
// Use the overload of WriteLine that accepts string format and arguments
writer.WriteLine("{0}, {1}, {2}", reply.Status, reply.RoundtripTime, reply.Address);
}
}
catch
{
// You had a syntax error here
Console.WriteLine("ERROR: You have some TIMEOUT issue");
}
}
Ok I have most of this figured out. Thank you all so much for helping me.
Although, I still need this to ping at least three more websites and give me 4 ping results per website.
So if someone could please, please just help me out a little bit more.
Here is what I have and this so far it works:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace Ping Application
{
class Program
{
static void Main(string[] args)
{
string filename = #"PingLog.csv";
{
using (var writer = new StreamWriter(filename, true))
{
writer.WriteLine("www.yahoo.com", Time in MilliSeconds);
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send("www.yahoo.com", 1000);
if (reply != null)
{
Console.WriteLine("{0}, {1}, {2}", reply.Address, reply.RoundtripTime, reply.RoundtripTime);
}
}
catch
{
Console.WriteLine.("ERROR: You have some TIMEOUT issue");
}
}
}
}
}
}

WCF With NetTCP across machines on the same network

I'm trying to implement some cross process communication that is between multiple computers and one server on the same network. What I'm trying right now is to use WCF with NetTcpBinding, hosted within my application which works on the same machine, but when I try to connect from another machine it throws a SSPI security error.
I've found lots of examples of doing this cross-machine, but all involve an app.config file which I would REALLY like to avoid. I want to be able to embed this functionality in a DLL that has not other dependencies (i.e. config files) for which I can just pass into it all of the necessary server addresses, etc and it will work. Is there anyway to setup this security (via the endpoints, etc) purely in code?
I'm testing this all out with the code below:
SERVER:
using System;
using System.ServiceModel;
namespace WCFServer
{
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
public class StringReverser : IStringReverser
{
public string ReverseString(string value)
{
char[] retVal = value.ToCharArray();
int idx = 0;
for (int i = value.Length - 1; i >= 0; i--)
retVal[idx++] = value[i];
string result = new string(retVal);
Console.WriteLine(value + " -> " + result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
var uri = "net.tcp://" + System.Net.Dns.GetHostName() + ":9985";
Console.WriteLine("Opening connection on: " + uri);
using (ServiceHost host = new ServiceHost(
typeof(StringReverser),
new Uri[]{
new Uri("net.tcp://" + System.Net.Dns.GetHostName() + ":9985")
}))
{
host.AddServiceEndpoint(typeof(IStringReverser),
new NetTcpBinding(),
"TcpReverse");
host.Open();
Console.WriteLine("Service is available. " +
"Press <ENTER> to exit.");
Console.ReadLine();
host.Close();
}
}
}
}
CLIENT:
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace WCFClient
{
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
class Program
{
static void Main(string[] args)
{
var ep = "net.tcp://SERVER:9985/TcpReverse";
ChannelFactory<IStringReverser> pipeFactory =
new ChannelFactory<IStringReverser>(
new NetTcpBinding(),
new EndpointAddress(
ep));
IStringReverser pipeProxy =
pipeFactory.CreateChannel();
Console.WriteLine("Connected to: " + ep);
while (true)
{
string str = Console.ReadLine();
Console.WriteLine("pipe: " +
pipeProxy.ReverseString(str));
}
}
}
}
Security is normally configured on the binding. You are using NetTcpBinding with its defaults which means that Transport security is enabled.
On both, server and client, you should assign the NetTcpBinding instance to a local variable so that you can change the security (and possibly other) settings, and then use that variable when calling AddServiceEndpoint or when creating the ChannelFactory.
Sample:
var binding = new NetTcpBinding();
// disable security:
binding.Security.Mode = SecurityMode.None;
This is probably an issue with the SPN that your service is running under. It's most likely a machine account instead of a domain account. There's more information in this thread.
UPDATE: There's information in there about setting the SPN programmatically, but it's buried a few clicks in... here's a direct link (see the last section of the page).

Categories

Resources