Can't CREATE an MSMQ Multicast Queue - c#

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

Related

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!

How to get message constantly from remote IBM MQ

I created a windows service that will connect to remote MQ and get the message as MQSTR format but after getting the message I didn't closed connection to remote MQ . My windows service will continuously check if data is available in remote MQ or not but after getting one message I need to restart my service to get the another message from remote MQ . Can anyone tell me what I need to do to get message constantly from remote MQ . Any clue or any link will do fine . Please Help
My C# windows service code is like this :
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace MQ_listner
{
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
Service1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MQ_listner
{
public partial class Service1 : ServiceBase
{
private MQReader MQReader;
private string _serviceName = "MQ_Listener";
private DateTime _TimeStart;
private bool _run = true;
private Thread _thread;
int WaitWhenStop = 0;
private DateTime _TimeEnd;
private TimeSpan _TimeDifference;
private TimeSpan _TimeElasped = new TimeSpan(0);
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
EventLog.WriteEntry(_serviceName + "was started at" + _TimeStart.ToString());
_run = true;
_thread = new Thread(new ThreadStart(StartMQListenerService));
_thread.IsBackground = true;
_thread.Start();
}
catch (Exception ex)
{
EventLog.WriteEntry(_serviceName + "was not started . Error Message : " + ex.ToString());
}
}
protected override void OnStop()
{
_run = false;
_thread.Join(WaitWhenStop);
_TimeEnd = DateTime.Now;
_TimeDifference = _TimeEnd.Subtract(_TimeStart);
_TimeElasped = _TimeElasped.Add(_TimeDifference);
EventLog.WriteEntry(_serviceName + "was stopped at " + _TimeEnd.ToString() + "\r\n ran for total time :" + _TimeElasped.ToString());
}
// MQ connection service
public void StartMQListenerService()
{
try
{
if (_run)
{
if (MQReader == null)
{
MQReader = new MQReader();
MQReader.InitializeConnections();
EventLog.WriteEntry(_serviceName + "MQ connection is established");
}
}
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry(_serviceName, ex.ToString());
System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
startinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startinfo.FileName = "NET";
startinfo.Arguments = "stop" + this.ServiceName;
Process.Start(startinfo);
}
}
}
}
****MQReader.cs****
using System;
using IBM.WMQ;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Configuration;
namespace MQ_listner
{
internal class MQReader
{
public MQReader()
{
}
public void InitializeConnections()
{
MQQueueManager queueManager;
MQMessage queueMessage;
MQGetMessageOptions queueGetMessageOptions;
MQQueue queue;
string QueueName;
string QueueManagerName;
string ChannelInfo;
string channelName;
string PortNumber;
string transportType;
string connectionName;
QueueManagerName = ConfigurationManager.AppSettings["QueueManager"];
QueueName = ConfigurationManager.AppSettings["Queuename"];
ChannelInfo = ConfigurationManager.AppSettings["ChannelInformation"];
PortNumber = ConfigurationManager.AppSettings["Port"];
char[] separator = { '/' };
string[] ChannelParams;
ChannelParams = ChannelInfo.Split(separator);
channelName = ConfigurationManager.AppSettings["Channel"];
transportType = ConfigurationManager.AppSettings["TransportType"];
connectionName = ConfigurationManager.AppSettings["ConnectionName"];
String strReturn = "";
try
{
queueManager = new MQQueueManager(QueueManagerName,
channelName, connectionName);
strReturn = "Connected Successfully";
queue = queueManager.AccessQueue(QueueName,
MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
queueMessage = new MQMessage();
queueMessage.Format = MQC.MQFMT_STRING;
queueGetMessageOptions = new MQGetMessageOptions();
queue.Get(queueMessage, queueGetMessageOptions);
strReturn = queueMessage.ReadString(queueMessage.MessageLength);
}
catch (MQException exp)
{
strReturn = "Exception: " + exp.Message;
}
string path1 = #"C:\documents\Example.txt";
System.IO.File.WriteAllText(path1, strReturn);
}
}
}
Can anyone tell me what is wrong in my code? Do I need anything to add here to get message constantly from remote MQ . Please Help . Any link or clue will do fine .
EDIT
after certain amount of time I need to restart my service to fetch data from remote mq . Can you tell me why windows service needs to restart to fetch data . Any clue? any idea ?
Where is your queue close and queue manager disconnect? If you connect and/or open something, you must make sure you close and disconnect from it. I would strongly suggest you take an MQ programming course. Or go to the MQ Technical Conference which has sessions on programming MQ.
I posted a fully functioning C# MQ program that retrieves all of the messages on a queue at MQQueueManager message pooling
Here is an updated version of your MQReader class that should give you the right idea. Note: I did not test it. I leave that for you. :)
Also, you should be putting your connection information in a Hashtable and pass the Hashtable to the MQQueueManager class.
using System;
using IBM.WMQ;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Configuration;
namespace MQ_listner
{
internal class MQReader
{
private MQQueueManager qManager = null;
private MQMessage inQ = null;
private bool running = true;
public MQReader()
{
}
public bool InitQMgrAndQueue()
{
bool flag = true;
Hashtable qMgrProp = new Hashtable();
qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ConfigurationManager.AppSettings["ConnectionName"]);
qMgrProp.Add(MQC.CHANNEL_PROPERTY, ConfigurationManager.AppSettings["Channel"]);
try
{
if (ConfigurationManager.AppSettings["Port"] != null)
qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse(ConfigurationManager.AppSettings["Port"]));
else
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
catch (System.FormatException e)
{
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
if (ConfigurationManager.AppSettings["UserID"] != null)
qMgrProp.Add(MQC.USER_ID_PROPERTY, ConfigurationManager.AppSettings["UserID"]);
if (ConfigurationManager.AppSettings["Password"] != null)
qMgrProp.Add(MQC.PASSWORD_PROPERTY, ConfigurationManager.AppSettings["Password"]);
try
{
qManager = new MQQueueManager(ConfigurationManager.AppSettings["QueueManager"],
qMgrProp);
System.Console.Out.WriteLine("Connected Successfully");
inQ = qManager.AccessQueue(ConfigurationManager.AppSettings["Queuename"],
MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
System.Console.Out.WriteLine("Open queue Successfully");
}
catch (MQException exp)
{
System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
flag = false;
}
return flag;
}
public void LoopThruMessages()
{
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.Options |= MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING;
gmo.WaitInterval = 2500; // 2.5 seconds wait time or use MQC.MQEI_UNLIMITED to wait forever
MQMessage msg = null;
while (running)
{
try
{
msg = new MQMessage();
inQ.Get(msg, gmo);
System.Console.Out.WriteLine("Message Data: " + msg.ReadString(msg.MessageLength));
}
catch (MQException mqex)
{
if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE)
{
// no meesage - life is good - loop again
}
else
{
running = false; // severe error - time to exit
System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
}
catch (System.IO.IOException ioex)
{
System.Console.Out.WriteLine("ioex=" + ioex);
}
}
try
{
if (inQ != null)
{
inQ.Close();
System.Console.Out.WriteLine("Closed queue");
}
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
try
{
if (qMgr != null)
{
qMgr.Disconnect();
System.Console.Out.WriteLine("disconnected from queue manager");
}
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
}
public void StopIt()
{
running = false;
}
}
}
Whenever you stop the service, make sure it calls the StopIt method in MQReader.

Way to close TCP Connection and Exit Application

This is a TCP Program which receives data from a TCP connection, then parse it and transfer it to another TCP connection. When I exit application, it doesn't work. It will remain as a process in the system.
As I am not a very experienced developer, can someone please help me to find the error in this code..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Machine_Feeder
{
public partial class FeederControlMonitor : Form
{
TcpListener Listener = null;
public string Status = string.Empty;
public Thread T = null;
public FeederControlMonitor()
{
InitializeComponent();
}
private void FeederControlMonitor_Load(object sender, EventArgs e)
{
txtStatus.Text = "Feeder waiting for data...";
ThreadStart Ts = new ThreadStart(StartReceiving);
T = new Thread(Ts);
T.Start();
}
public void StartReceiving()
{
ReceiveTCP(9100);
}
public void ReceiveTCP(int portN)
{
try
{
Listener = new TcpListener(IPAddress.Any, portN);
Listener.Start();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\\Drive\\ex.txt", ex.Message);
Console.WriteLine(ex.Message);
}
try
{
while (true)
{
Socket client = Listener.AcceptSocket();
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[10000];
int size = client.Receive(data);
ParseData(System.Text.Encoding.Default.GetString(data));
client.Close();
});
childSocketThread.Start();
}
Listener.Stop();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\\Drive\\ex.txt", ex.Message);
}
}
public void ParseData(string data)
{
var useFulData = data.Substring(data.IndexOf("F1")).Replace(" ", " ");// Space
useFulData = useFulData.Remove(useFulData.IndexOf("<ETX>"));
string[] delimeters = { "<DEL>", "<ESC>" };
var listOfValues = useFulData.Split(delimeters, StringSplitOptions.None).ToList();
int pos = 0;
for (int i = 1; i < listOfValues.Count; i += 2, pos++)
{
listOfValues[pos] = listOfValues[i];
}
listOfValues.RemoveRange(pos, listOfValues.Count - pos);
txtHealthCard.Invoke((Action)delegate { txtHealthCard.Text = listOfValues[0]; });
txtCID.Invoke((Action)delegate { txtCID.Text = listOfValues[1]; });
txtMedicalFitLocation.Invoke((Action)delegate { txtMedicalFitLocation.Text = listOfValues[2]; });
txtGender.Invoke((Action)delegate { txtGender.Text = listOfValues[3]; });
txtAge.Invoke((Action)delegate { txtAge.Text = listOfValues[4]; });
txtPatientName.Invoke((Action)delegate { txtPatientName.Text = listOfValues[5]; });
MyProtocolMaker(listOfValues[5],
listOfValues[4],
listOfValues[2],
listOfValues[3],
listOfValues[8],
listOfValues[1],
listOfValues[10],
);
}
private void btnExit_Click(object sender, EventArgs e)
{
Listener.Stop();
T.Abort();
this.Close();
}
private void MyProtocolMaker(
string patientName,
string patientAge,
string mfitLocation,
string gender,
string healthCardNo,
)
{
string feederInfo = "^^^P^PI" + healthCardNo + "^PN" + patientName + "^PA" + patientAge + "^PS" + gender + "^P7" + mfitLocation +"^_SS^^^_S";
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient("127.0.0.1", 8001);
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(feederInfo);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
serverStream.Close();
clientSocket.Close();
}
private void FeederControlMonitor_FormClosing(object sender, FormClosingEventArgs e)
{
Listener.Stop();
T.Abort();
this.Close();
}
}
}
You problem is, that you are creating threads within the thread. These threads are keeping the application alive. Try marking them as background threads: (This is red-tape solution)
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[10000];
int size = client.Receive(data); // <-- the thread hangs on these and will block termination
ParseData(System.Text.Encoding.Default.GetString(data));
client.Close();
});
childSocketThread.IsBackground = true; // <---
childSocketThread.Start();
When thread are not marked as background (default), they will block application termination. You should create a list to store the client threads, so you can exit those threads nicely.
You should never abort a thread, unless there is no other way. Instead of aborting, you should exit the while loop in the thread.
As nice way is using a ManualResetEvent:
fields:
private ManualResetEvent _terminating = new ManualResetEvent(false);
in thread:
while (_terminating.WaitOne(0))
{
// thread code
}
on exit:
_terminating.Set();
T.Join();
Sidenote: TCP is streaming, so just reading 10k of bytes ones, does not guarantee a complete packet.

Get all IP adresses on LAN

I have a program that ping and take all the ip address that are active in a LAN i code it with csharp console mode the problem is that when I put it in mode form an error appear in Spinwatch and a error message box appear
Here is the code and error below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Threading;
namespace pingagediffusiontest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{ }
private static List<Ping> pingers = new List<Ping>();
private static int instances = 0;
private static object #lock = new object();
private static int result = 0;
private static int timeOut = 250;
private static int ttl = 5;
static void Mains()
{
string baseIP = "192.168.1.";
Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP);
CreatePingers(255);
PingOptions po = new PingOptions(ttl, true);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] data= enc.GetBytes("abababababababababababababababab");
SpinWait wait = new SpinWait();
int cnt = 1;
Stopwatch watch = Stopwatch.StartNew();
foreach (Ping p in pingers) {
lock (#lock) {
instances += 1;
}
p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
cnt += 1;
}
while (instances > 0) {
wait.SpinOnce();
}
watch.Stop();
DestroyPingers();
Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
Console.ReadKey();
}
public static void Ping_completed(object s, PingCompletedEventArgs e)
{
lock (#lock) {
instances -= 1;
}
if (e.Reply.Status == IPStatus.Success) {
Console.WriteLine(string.Concat("Active IP: ", e.Reply.Address.ToString()));
result += 1;
} else {
Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString()))
}
}
private static void CreatePingers(int cnt)
{
for (int i = 1; i <= cnt; i++) {
Ping p = new Ping();
p.PingCompleted += Ping_completed;
pingers.Add(p);
}
}
private static void DestroyPingers()
{
foreach (Ping p in pingers) {
p.PingCompleted -= Ping_completed;
p.Dispose();
}
pingers.Clear();
}
}
}
Error 1 The type or namespace name 'SpinWait' could not be found
Error 3 The type or namespace name 'Stopwatch' could not be found
Error 4 The name 'Stopwatch' does not exist in the current context
Just add the
using System.Diagnostics;
At the top of your file.
Error 3 The type or namespace name 'Stopwatch' could not be found
You need to import following namespace to use StopWatch in your program:
using System.Diagnostics;
as suggested by #CodeCaster in comments - you are missing semicolon to terminate the Console.WriteLine() statement :
Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString())) //missing semicolon
Suggestion : as you have stated you converted code from Console Application to Windows Forms Application it would be nice if you can change/replace all Console.WriteLine() Statements with MessageBox.Show() as shown below:
MessageBox.Show(String.Concat("Non-active IP: ", e.Reply.Address.ToString()));

C# how to stop the program after a certain time?

I have a big problem, but probably it's only big for me :). "terminal.Bind(client);" this line causes my program to hang if IP is bad. I want to stop this program after 5s working because if IP is wrong after 10s all program is hang.. :(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rebex.TerminalEmulation;
using Rebex.Security;
using Rebex.Net;
namespace Routers_info_v._1
{
class Program
{
static void Main(string[] args)
{
Telnet client = new Telnet("192.168.1.1");
VirtualTerminal terminal = new VirtualTerminal(80, 25);
terminal.Bind(client);
terminal.SendToServer("pass\r");
terminal.SendToServer("sys ver\r");
TerminalState state;
do
{
state = terminal.Process(2000);
} while (state == TerminalState.DataReceived);
terminal.Save("terminal.txt", TerminalCaptureFormat.Text, TerminalCaptureOptions.DoNotHideCursor);
terminal.Unbind();
terminal.Dispose();
}
}
}
Try to wrap the call in a try catch (assuming some exception is thrown):
try
{
terminal.Bind(client);
}
catch(Exception ex)
{
return;
}
You could kick off the Bind in a thread, and start a timer, if the thread takes X seconds too long to complete, you could kill the thread, or your application, whichever you choose.
You can use Task.Wait. Here is little simulation for an operation which will take 10 sec and you are waiting it for 5 sec to finish :)
using System;
using System.Linq;
using System.Data.Linq;
using System.Data;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class VirtualTerminal
{
public VirtualTerminal(int a, int b) { }
public bool Bind() { System.Threading.Thread.Sleep(10000); return true; }
}
class Program
{
static void Main(string[] args)
{
VirtualTerminal terminal = new VirtualTerminal(80, 25);
Func<bool> func = () => terminal.Bind() ;
Task<bool> task = new Task<bool>(func);
task.Start();
if (task.Wait(5*1000))
{
// you got connected
}
else
{
//failed to connect
}
Console.ReadLine();
}
}
}
I would suggest to put the network stuff into a second thread, which then may be aborted by the main thread.
class Program {
static void Main(string[] args) {
Thread thread = new Thread(threadFunc);
thread.Start();
Stopwatch watch = new Stopwatch();
watch.Start();
while (watch.ElapsedMilliseconds < 5000 && thread.IsAlive)
;
if (!thread.IsAlive) {
thread.Abort();
Console.WriteLine("Unable to connect");
}
}
private static void threadFunc() {
Telnet client = new Telnet("192.168.1.1");
VirtualTerminal terminal = new VirtualTerminal(80, 25);
terminal.Bind(client);
// ...
terminal.Dispose();
}
}

Categories

Resources