TcpClient disconnects after awhile from Twitch IRC - c#

My issue is that after I connect to the IRC and I am receiving raw text from the IRC and logging it but then it just decides to disconnect from the server after inactivity or 2-3 seconds after I start it (unconfirmed).
Any help would be appreciated. Here's my code (had issues posting it here):
http://pastebin.com/Ls5rv0RP
I need it to stop disconnecting but I cant really find a way to. I know the popular mIRC client disconnects from Twitch after x amount of time but reconnects and that's fine to as long as it KNOWS to reconnect in a timely manner (2-5 seconds).
The part were it replys to PING/PONG's:
if (buf.StartsWith("PING ")) output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush();
Any help is appreciated.

This code below helps keep my Twitch bot from disconnecting by running a separate thread that pings to the IRC server.
PingSender Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TwitchBot
{
/*
* Class that sends PING to irc server every 5 minutes
*/
class PingSender
{
static string PING = "PING ";
private Thread pingSender;
// Empty constructor makes instance of Thread
public PingSender()
{
pingSender = new Thread (new ThreadStart (this.Run) );
}
// Starts the thread
public void Start()
{
pingSender.Start();
}
// Send PING to irc server every 5 minutes
public void Run()
{
while (true)
{
Program.irc.sendIrcMessage(PING + "irc.twitch.tv");
Thread.Sleep(300000); // 5 minutes
}
}
}
}
Usage:
/* Ping to twitch server to prevent auto-disconnect */
PingSender ping = new PingSender();
ping.Start();

Related

SignalR stays in the Connecting state when IIS doesn't respond to connect request

I'm having an issue when using SignalR and IIS on my Windows 10 machine. The problem is that IIS only allows for 10 concurrent connections. When The 10th connection is reached, the client side HubConnection will stay in the Connecting state for a long time.
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static int usedConnections = 0;
static void Main(string[] args)
{
Foo();
while (true) { }
}
static async void Foo()
{
for(int i = 0; i < 15; i++)
{
await SetupSignalR();
}
}
static async Task SetupSignalR()
{
//Set connection
var hub = new HubConnection("http://MyComputer/MyIISApp");
hub.TraceLevel = TraceLevels.All;
hub.TraceWriter = Console.Out;
//Make proxy to hub based on hub name on server
var myHub = hub.CreateHubProxy("MyIISHub");
//Start connection
hub.TransportConnectTimeout = TimeSpan.FromSeconds(5);
await hub.Start();
usedConnections++;
Console.WriteLine($"Used Conenctions: {usedConnections}");
return;
}
}
}
After a reasonable period of time I would like to display a message to the user that the HubConnection is unable to connect to the server, but I cant figure out how to either set a timeout or trigger an event. What can I do to notify the user that IIS isn't accepting the connection request?
According to your description, I suggest you could try to write the codes to monitor the connection time, if the time has exceed the 30 seconds, you could directly stop connect to the signlar server and show a error message.
Besides, the connection limit for the IIS is only happened on the windows10. If you used the windows server, there is no limit for the IIS connection.

Connection closes after few seconds when connecting to ActiveMQ set up on AWS

I am connecting to Apache Active MQ which is hosted on AWS to integrate my app to a custom service. I need to keep this running always, not one time like it's right now. The code below works, but only for one message, I need to maintain the connection active all the time listening in order to receive all the messages.
Here is the code.
using Apache.NMS;
using Apache.NMS.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ApacheMQAsync
{
class Program
{
protected static ITextMessage message = null;
public static void Main(string[] args)
{
Uri connecturi = new Uri("URL:61617");
Console.WriteLine("About to connect to " + connecturi);
// NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connecturi);
IConnection connection = factory.CreateConnection("username", "password");
ISession session = connection.CreateSession();
IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");
Console.WriteLine("Using destination: " + destination);
// Create a consumer and producer
IMessageConsumer consumer = session.CreateConsumer(destination);
consumer.Listener += new MessageListener(OnMessage);
connection.Start();
// Wait for the message
if (message == null)
{
Console.WriteLine("No message received!");
}
else
{
Console.WriteLine("Received message with ID: " + message.NMSMessageId);
Console.WriteLine("Received message with text: " + message.Text);
}
}
protected static void OnMessage(IMessage receivedMsg)
{
message = receivedMsg as ITextMessage;
message.Acknowledge();
}
}
}
On the console it displays following
No message received!
and after few seconds the console exist?
There's no real magic there, you need to do something to keep your application running such as pausing on console input or looping on a sleep or other wait type call and then checking something to see if your application should continue. The JMS client isn't guaranteed to keep your application open and running and you should never rely on it to.

C# tcp stream - is it possible to run stream without listener?

I want to write a part of code in which I start sending packages using tcp stream, but without any part that receives it over the internet.
In the meantime I would also like to have another method that can connect to that particular stream at any time and starts receiving bytes from the moment it connects.
I wanted to use multicasting, but I see it's impossible to do it over the Internet
Is there a way to do it? I only found some info so far, that the tcp connection in C# uses point to point way, so my case sounds impossible to implement, because the listener has to be always active to even initialize the streamer, how can I bypass that?
Edit Added an example of a simply "broker" who republishes all messages it receives.
Either use UDP and broadcast your packets to an endpoint that may or maynot be listening at any point in time.
Or use a message queue such as MSMQ, RabbitMQ or 0MQ.
MSMQ may become a problem if the listening service is offline for to long as the messages queue on your dispatch system resulting in a backlog that may fill.
If you would like to create something using UDP here is some code.
Listener (server):
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UDPLISTENER
{
class Program
{
static void Main(string[] args)
{
var port = 8750;
var listener = new UdpClient(port);
var group = new IPEndPoint(IPAddress.Any, port);
Console.WriteLine("Listening for datagrams on port {0}", port);
while(true)
{
var data = listener.Receive(ref group);
Console.WriteLine("{0}: {1}", group.ToString(), Encoding.Default.GetString(data, 0, data.Length));
}
}
}
}
Broker (Server&Client):
sing System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UDPCLIENT
{
class Program
{
static void Main(string[] args)
{
int listeningPort = 8749, dispatchPort = 8750;
var listener = new UdpClient(listeningPort);
var group = new IPEndPoint(IPAddress.Any, listeningPort);
// Republish client
var sender = new UdpClient("127.0.0.1", dispatchPort);
Console.WriteLine("Listening for datagrams on port {0}", listeningPort);
while (true)
{
var data = listener.Receive(ref group);
Console.WriteLine("{0}: {1}", group.ToString(), Encoding.Default.GetString(data, 0, data.Length));
sender.Send(data, data.Length);
}
}
}
}
Sender (Client):
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UDPSENDER
{
class Program
{
static void Main(string[] args)
{
var sender = new UdpClient("127.0.0.1", 8749);
while (true)
{
Console.WriteLine("Message: ");
var data = Encoding.Default.GetBytes(Console.ReadLine());
sender.Send(data, data.Length);
}
}
}
}
Depending what you wish to archive I recommend message queues they give to the most flexibility.
But as you can see UDP works a bit differently to TCP. You don't need a handshake like TCP does, this means if no one is listening to your messages they vanish with no cost to the sender (there is still cost to the network). But if a listener pops up then they start consuming the messages right away. Remember no UDP packet is guaranteed delivery, this is both a blessing and a curse.
If you want messages to be guaranteed you need to implement your own solution, one method is a counter on the datagrams that the listener watches if there is a message missing then it request that message be resent.
You can create a new class derived from Stream, override the Write method, and manage the writing to the tcp clients here. You will be able to write to this stream from your code whether a client is connected or not. When no client is connected, the data will simply be ignored.

WPF C# application will freeze my whole computer ever 2-3 times I run it

I put a lot of information in this issue because I have no idea what will be relavent
Issue:
I am having an issue with a program I am working on where when running it, it will freeze my whole computer and return no error (I am completely incapable of doing anything CTRL+ALT+DEL doesn't even work). This program accepts a connection from a android client and atm the android client is not configured correctly so the connection is being rejected.
Question:
How can I stop my program from freezing my entire machine?
Conjecture:
I have a few theories as to what is going on but no idea how to fix them. I have read that this may have something to do with me running a single threaded process inside my async worker but I am not sure that the socket is a single threaded process. Also I am not entirely sure how I am supposed to deal with exceptions in a backgroundworker so I just let it fall back to the RunWorkerCompletedEventArgs then retrieve the error message from there.
What I have tried:
- I tried putting try catches every where then removing try catches nothing seems to be able to capture this error
- I checked my systems event log and nothing is showing up except my restarts after my computer freezes
- I have attempted to isolate the issue but it can literally happen at any point from the program starting till when I attempt to connect
Setup:
I am running the program out of visual studio 2012 professional on a windows 8 pro machine. The computer I am on has a i7-3770K 3.50GHz and 32GB of ram. The application that is attempting to make a connection to mine is a Android application and the credentials are incorrect when it is attempting to connect. Visual Studio is running off my main hard drive and building the project on another drive.
Closing:
With all that said would some one please be willing to help me? If you need any more information I will be happy to provide it, please ask.
Main Method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace Server
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class SourceServer : Window
{
private BackgroundWorker worker = new BackgroundWorker();
public SourceServer()
{
InitializeComponent();
StartListeningForConnections();
}
private void StartListeningForConnections()
{
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.WorkerReportsProgress = true;
if (worker.IsBusy != true)
{
worker.RunWorkerAsync();
}
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
worker.ReportProgress(0, "Source server version 0.0.0.1ib started");
LoginServer oLoginServer = new LoginServer();
oLoginServer.StartListening(worker);
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
lvOutput.Items.Add(e.UserState.ToString());
}
catch (Exception exception)
{
lvOutput.Items.Add(exception.StackTrace);
}
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
System.IO.File.WriteAllText(Environment.CurrentDirectory + #"\log.txt", e.Error.StackTrace + " /n " + e.Error.Message);
}
else
{
MessageBox.Show("Error was null");
}
worker.Dispose();
}
}
}
SSL Socket Connection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using MySql.Data.MySqlClient;
using System.IO;
namespace Server
{
public class LoginServer
{
// Incoming data from the client.
public static string data = null;
public static X509Certificate serverCertificate = null;
public delegate void UpdateListView(ListView oOutput);
public void StartListening(BackgroundWorker worker)
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
serverCertificate = X509Certificate.CreateFromCertFile(#"server.crt");
TcpListener oServer = new TcpListener(ipAddress, 12345);
// Bind the socket to the local endpoint and
// listen for incoming connections.
// Start listening for connections.
while (true)
{
Thread.Sleep(100);
worker.ReportProgress(0, "Waiting for connection....");
// Program is suspended while waiting for an incoming connection.
//Socket handler = listener.Accept();
oServer.Start();
TcpClient oClient = oServer.AcceptTcpClient();
Stream oStream = oClient.GetStream();
SslStream oSSLStream = new SslStream(oStream);
data = null;
// An incoming connection needs to be processed.
string sUsername = "place holder";
string sPassword = "place holder";
while (true)
{
bytes = new byte[1024];
int bytesRec = oSSLStream.Read(bytes, 0, bytes.Length);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
string[] sCredentials = data.Split("|".ToCharArray()[0]);
sUsername = sCredentials[0];
sPassword = sCredentials[1];
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
worker.ReportProgress(0, "Connection Recieved : ");
worker.ReportProgress(0, "Username: " + sUsername);
worker.ReportProgress(0, "Password: " + sPassword);
worker.ReportProgress(0, "");
// Echo the data back to the client.
byte[] msg;
if (sUsername.Equals("test") && sPassword.Equals("test"))
{
msg = Encoding.ASCII.GetBytes("approved<EOF>\n");
worker.ReportProgress(0, "approved");
oSSLStream.Write(msg, 0, msg.Length);
}
else
{
msg = Encoding.ASCII.GetBytes("rejected<EOF>\n");
worker.ReportProgress(0, "rejected");
oSSLStream.Write(msg, 0, msg.Length);
}
}
}
public void VerifyUser()
{
}
}
}
While I don't see any reason for this to lock up your entire computer, I do see a couple of reasons for the application to potentially hang...
Your while loop inside of your SSL server will never break unless your client writes '<EOF>' to the stream; which you would have to force it to do. I would likely do something similar to this:
while(( bytesRec = oSSLStream.Read(bytes,0,bytes.Length)) > 0 )
{
// Compare input & break
}
-- The while loop you have now ( without a thread sleep ) will consume all of your systems resources waiting for ... something that may never occur.
In a related issue - I note that your 'DoWork' method launches the listener - but does not start a new thread for this listener. This means that the listener is running inside of your interface thread - which will cause the interface ( and potentially more... ) to hang until the process is completed - which as stated, may never happen.
... Ahem... This last paragraph may be incorrect - you are running an async worker, so I may be incorrect in my second assessment.
Cheers, hope this is helpful.
I've had some hanging problems on Windows 8 that I never saw on Windows 7 (with VS2012). As you experienced it worked fine the first time but only locked up Visual Studio (and not my whole machine) and I had to force quit.
The Visual Studio 2012 Update 4 (which focuses on bug fixes and compatibility) seemed to fix it, although I didn't scientifically test this.
Note: As of 9/1/13 this is only the RC2 version so please check for newer versions, and edit this answer when RTM happens.

c# Serialport problem: data are send in "clumps"

I am trying to remote control a lego mindstorms NXT robot using a bluetooth serial connection. The program connects without any problem but when i send single commands they do not appear before several other commands has been send. Then they all appear at once on the nxt.
I have tried everything (i can think of or google has told me to) but i cannot seam to get the buffer to flush after a command is send.
Anyone having a idea about what i can do?
Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace NXTBtRemote
{
public class BTHandler
{
SerialPort comm;
private string comPort;
public BTHandler()
{
comm = new SerialPort();
}
public Boolean Connect(string _comPort)
{
this.comPort = _comPort;
comm.PortName = comPort;
comm.Open();
if (comm.IsOpen) return true;
else return false;
}
public void sendCommand(Command command)
{
string msg = command.cmdType + "#" + command.arguments;
if (!comm.IsOpen) comm.Open();
comm.WriteLine(msg);
comm.DiscardOutBuffer();
}
}
}
Hope somone can help. Thanks in advance
kind regards - kenneth
comm.DiscardOutBuffer();
That's very bad. You are throwing away the bytes you have just written. The WriteLine() method writes the command to the output buffer from which they are slowly written to the serial port. Only if you debug the code, single stepping through the code, would the serial port driver have enough of a chance to actually send something. It would be hit or miss if the chip itself has a FIFO buffer. Just delete the DiscardOutBuffer() call, it does nothing but harm.
Beyond that, you are really complaining about a problem with receiving a response. But didn't show any code that makes any Read call.

Categories