receive sms in c# - c#

I use this code for receive sms,but sometimes it does not work,it means it can not understand sms receive.what can i do that every time it works:
CommSetting.comm.MessageReceived+=new MessageReceivedEventHandler(comm_MessageReceived);
private void comm_MessageReceived(object sender, GsmComm.GsmCommunication.MessageReceivedEventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
string storage = GetMessageStorage();
DecodedShortMessage[]messages=CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread , storage);
foreach(DecodedShortMessage message in messages)
{
Output(string.Format("Message status = {0}, Location = {1}/{2}",
StatusToString(message.Status),
message.Storage, message.Index));
ShowMessage(message.Data);
Output("");
}
Output(string.Format("{0,9} messages read.", messages.Length.ToString()));
Output("");
}

Related

Q) c# Multi serialport receive solution?

private void Serial_Event_1(object sender, SerialDataReceivedEventArgs e)
{
bytes1 = 0;
if (received_Sequence == 0)
{
SerialPort sData = sender as SerialPort;
var th1 = new Thread(Serial_Event_Thread1);
try
{
bytes1 = sData.BytesToRead;
}
catch { }
byte[] read_data_ = new byte[bytes1];
linef_1 = new byte[bytes1];
try
{
// sData.Read(read_data_, 0, bytes1);
sData.Read(linef_1, 0, bytes2);
// linef_1 = read_data_;
}
catch
{
MessageBox.Show("1 handle error");
}
Invoke((MethodInvoker)delegate
{
th1.Start();
});
if (port_numbering > 1)
{
received_Sequence ++;
}
}
if (port_numbering == 1)
received_Sequence = 0;
}
private void Serial_Event_2(object sender, SerialDataReceivedEventArgs e)
{
//Same as receivedevent 1
}
private void Serial_Event_Thread1()
{
// The incoming data packets are analyzed and written to the richtextbox.
//Even when using two or more serial communication without `enter code here`analyzing packets, only one port can communicate smoothly.
//The `enter code here`other ports are not well received or do not work.
}
enter code here
The length of the data received is 18 bytes.
I've done it a lot with one Serialport communication.
Please give me a hint if you have implemented two or more Serial communications.
It uses a total of four " ReceivedEvent " and handles data with separate threads.
If you use two or more ports, the data is normally sent from one port to another, and the data is not broken or data is not received.
We try to connect a total of four ports using the " multi-serialport " approach.
You want to receive data sequentially from each number to a sample of 20 ms.
Each " serialdatareceivevent " occurs, and data is displayed once a second.
I'm not sure how to correct it, but please help me.
Thank you for reading it here.
I'll be looking forward to your help.
private void Serial_btn_1_Click(object sender, EventArgs e)
{
Test_Timer.Interval = 15;
Test_Timer.Tick += new System.EventHandler(TimerEventProcessor);
Test_Timer.Start();
}
private void TimerEventProcessor(object sender, EventArgs e)
{
try
{
bytes1 = serialPort1.BytesToRead;
bytes1 = serialPort2.BytesToRead;
bytes1 = serialPort3.BytesToRead;
bytes1 = serialPort4.BytesToRead;
linef_1 = new byte[bytes1];
linef_2 = new byte[bytes2];
linef_3 = new byte[bytes3];
linef_4 = new byte[bytes4];
}
catch { }
try
{
serialPort1.Read(linef_1, 0, bytes1);
serialPort2.Read(linef_2, 0, bytes2);
serialPort3.Read(linef_3, 0, bytes3);
serialPort4.Read(linef_4, 0, bytes4);
}
catch
{
// MessageBox.Show("Read_data no");
}
Invoke((MethodInvoker)delegate
{
richTextBox1.AppendText(ByteToHex(linef_1));
richTextBox2.AppendText(ByteToHex(linef_2));
richTextBox3.AppendText(ByteToHex(linef_3));
richTextBox4.AppendText(ByteToHex(linef_4));
});
}
Timer speed 15ms.
Changed to the above source.
Can I get a problem when I receive data using a timer?

Timer to track websocket sharp messages in c#

I am using a websocket sharp dll in my windows application to get messages from a GDAX server. Everything is working fine so far - the messages are coming and i am processing them. The point where I am stuck is when the messages stops coming. At least I don't find anything in the WebSocket.OnMessage Event(https://github.com/sta/websocket-sharp) that can help me in tracking when the messages are stopped (I tried emitonping also)
Now the messages I received have a message type 'Heartbeat' which is sent every second. I want to add a separate timer control to check if the heartbeat messages are coming every second or not and if it stops coming then I will need to reconnect the server again. But since nothing happens when the messages stops coming how do i track it, where should I put the timer code to check when heartbeat messages stops coming?
I hope I could explain the situation wherein I am struck. If someone is eager to help me and needs more inputs please let me know.
Update
private void _3_Load(object sender, EventArgs e)
{
ConnectAndGetWebsocketFeedMessages();
}
public delegate void WSOpen(string text);
public delegate void WSMessage(string message);
public delegate void WSError(string text);
public delegate void WSClose(string text);
private static string _endPoint = "wss://ws-feed.gdax.com";
WebSocket ws = new WebSocket(_endPoint);
private bool IsConnected { get; set; }
private string ProductId { get; set; }
string productId = "LTC-EUR";
ConcurrentQueue<string> concurrentQueue = new ConcurrentQueue<string>();
public void SetWebSocketSharpEvents()
{
ws.Log.Level = LogLevel.Trace;
ws.OnOpen += (sender, e) =>
{
IsConnected = true;
OnWSOpen("Connection Status :: Connected *********");
};
ws.EmitOnPing = true;
ws.OnMessage += (sender, e) =>
{
if (e.IsPing)
{
OnWSMessage("ping received");
}
else
{
OnWSMessage(e.Data);
}
};
ws.OnError += (sender, e) =>
{
IsConnected = false;
OnWSError(e.Message); //An exception has occurred during an OnMessage event. An error has occurred in closing the connection.
if (ws.IsAlive)
ws.Close();
};
ws.OnClose += (sender, e) =>
{
IsConnected = false;
OnWSClose("Close");
};
ws.ConnectAsync();
}
private void ConnectAndGetWebsocketFeedMessages()
{
SetWebSocketSharpEvents();
}
private void SubscribeProduct(string sProductID)
{
if (IsConnected)
{
ProductId = sProductID;
string data = "{\"type\": \"subscribe\", \"product_ids\": [\"" + sProductID + "\"]}";
ws.Send(data);
ws.Send("{\"type\": \"heartbeat\", \"on\": true}");
}
}
void OnWSOpen(string text)
{
SubscribeProduct(productId);
timer1.Interval = 1000;
timer1.Tick += timer1_Tick;
timer1.Start();
}
DateTime lastHeartbeatTime = DateTime.MinValue;
bool isTimerStart = false;
void OnWSMessage(string message)
{
concurrentQueue.Enqueue(message);
SaveHeartbeatMessageTime(message);
ProcessMessage(message);
}
private void SaveHeartbeatMessageTime(string jsonString)
{
var jToken = JToken.Parse(jsonString);
var typeToken = jToken["type"];
var type = typeToken.ToString();
if (type == "heartbeat")
{
lastHeartbeatTime = DateTime.Now;
this.Invoke(new MethodInvoker(delegate()
{
lbllastheartbeat.Text = lastHeartbeatTime.ToLongTimeString();
}));
}
}
private void ProcessMessage(string message) { }
void OnWSError(string text) { }
void OnWSClose(string text) { }
bool isMessagesReceived = false;
private void timer1_Tick(object sender, EventArgs e) // it stops working as soon as lbllastheartbeat gets some value
{
DateTime currentTime = DateTime.Now;
TimeSpan duration = currentTime.Subtract(lastHeartbeatTime);
this.Invoke(new MethodInvoker(delegate()
{
lblNow.Text = currentTime.ToLongTimeString();
}));
if (Int16.Parse(duration.ToString("ss")) > 1)
{
// reconnect here
}
}
Edit
I am using windows form timer control and it keeps on calling timer1_Tick method and does not call OnWSMessage method. How do I ensure that both run parallel and if any message is missed or the message stops coming then it reconnects?
Edit2
The solutions provided below suggests to add the timer functionality in onMessage event but what will happen if I do not receive messages? If the messages are not received then the code does not do anything. I have taken a global variable and whenever a message comes it adds the time in that variable. Now I want to run a separate timer control which will check whether there is anything in that variable and if its value i.e difference of seconds is more than 1 then do something else keep on checking.
Is there anyone who can look into this and advise please.
Update2: I still want to do this with windows.timer control and not threading.timer. I have taken two labels in my windows app, lbllastheartbeat (to show the time when heartbeat message is received) and lblNow (to show the current time when timer is called).
Requirement - My timer will check if any heartbeat message is missed and that is done through the 'lastHeartbeatTime' variable which stores the time when the heartbeat message is received.
I would appreciate if anyone can review my code and suggest what or where I am doing wrong.
The answer has already been given - you need to start timer which will fire after your timeout period when you receive message, and reset that timer every time you receive message. But it seems you want code example, so here it is (with comments):
System.Threading.Timer _timeoutTimer;
private readonly object _timeoutTimerLock = new object();
private void ResetTimeoutTimer() {
// if you are sure you will never access this from multiple threads at the same time - remove lock
lock (_timeoutTimerLock) {
// initialize or reset the timer to fire once, after 2 seconds
if (_timeoutTimer == null)
_timeoutTimer = new System.Threading.Timer(ReconnectAfterTimeout, null, TimeSpan.FromSeconds(2), Timeout.InfiniteTimeSpan);
else
_timeoutTimer.Change(TimeSpan.FromSeconds(2), Timeout.InfiniteTimeSpan);
}
}
private void StopTimeoutTimer() {
// if you are sure you will never access this from multiple threads at the same time - remove lock
lock (_timeoutTimerLock) {
if (_timeoutTimer != null)
_timeoutTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
}
private void ReconnectAfterTimeout(object state) {
// reconnect here
}
public void SetWebSocketSharpEvents() {
ws.Log.Level = LogLevel.Trace;
ws.OnOpen += (sender, e) => {
// start timer here so that if you don't get first message after 2 seconds - reconnect
ResetTimeoutTimer();
IsConnected = true;
OnWSOpen("Connection Status :: Connected *********");
};
ws.EmitOnPing = true;
ws.OnMessage += (sender, e) => {
// and here
ResetTimeoutTimer();
if (e.IsPing) {
OnWSMessage("ping received");
}
else {
OnWSMessage(e.Data);
}
};
ws.OnError += (sender, e) => {
// stop it here
StopTimeoutTimer();
IsConnected = false;
OnWSError(e.Message); //An exception has occurred during an OnMessage event. An error has occurred in closing the connection.
if (ws.IsAlive)
ws.Close();
};
ws.OnClose += (sender, e) => {
// and here
StopTimeoutTimer();
IsConnected = false;
OnWSClose("Close");
};
ws.ConnectAsync();
}
from your question what i understand is , your message is sending after every seconds , but the problem is only when it stop you want to know and run it again, if it like that , you just apply timer and check for every seconds if the message not sent after a second or more (check sentMessage() Method set a boolean if message sent it should give true otherwise false) , than give the command to reconnect the server again .

How to check message arrival in service bus at every 20 seconds?

I am using Service Bus of azure which will hold my list of messages means messages can enter in service bus at any time.
So i want to keep a watch on my service bus to check that whether any message is there in service or not.It is like i just want to keep a watch on my service bus regarding message arrival in my service bus at interval 0f 20 seconds.
In Every 20 Seconds i would like to check message arrival in my service bus and this i want to perform in background asynchronously.
I want to call below method in every 20 seconds in background:
private static void ReceiveMessages()
{
// For PeekLock mode (default) where applications require "at least once" delivery of messages
SubscriptionClient agentSubscriptionClient = SubscriptionClient.Create(TopicName, "AgentSubscription");
BrokeredMessage message = null;
while (true)
{
try
{
//receive messages from Agent Subscription
message = agentSubscriptionClient.Receive(TimeSpan.FromSeconds(5));
if (message != null)
{
Console.WriteLine("\nReceiving message from AgentSubscription...");
Console.WriteLine(string.Format("Message received: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>()));
// Further custom message processing could go here...
message.Complete();
}
else
{
//no more messages in the subscription
break;
}
}
catch (MessagingException e)
{
if (!e.IsTransient)
{
Console.WriteLine(e.Message);
throw;
}
else
{
HandleTransientErrors(e);
}
}
}
// For ReceiveAndDelete mode, where applications require "best effort" delivery of messages
SubscriptionClient auditSubscriptionClient = SubscriptionClient.Create(TopicName, "AuditSubscription", ReceiveMode.ReceiveAndDelete);
while (true)
{
try
{
message = auditSubscriptionClient.Receive(TimeSpan.FromSeconds(5));
if (message != null)
{
Console.WriteLine("\nReceiving message from AuditSubscription...");
Console.WriteLine(string.Format("Message received: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>()));
// Further custom message processing could go here...
}
else
{
Console.WriteLine("\nno more messages in the subscription");
//no more messages in the subscription
break;
}
}
catch (MessagingException e)
{
if (!e.IsTransient)
{
Console.WriteLine(e.Message);
throw;
}
}
}
agentSubscriptionClient.Close();
auditSubscriptionClient.Close();
}
So can anybody tell me how do i call this above method every 20 seconds?
The most beginner-friendly solution is:
Drag a Timer from the Toolbox, give it a Name, set your desired Interval and set "Enabled" to True. Then double click the Timer and Visual Studio (or whatever you are using) will write you the following Code:
private void wait_Tick(object sender, EventArgs e)
{
refreshText(); //add the method you want to call here.
}
or this
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
isonline()
}

TCPIP connection in c# and data sending/receiving in another threads

I have a problem with my TCPIP connection Form programm.
I have a code, where I'm trying to send and receive some data from server.
The main problem of my app is how to reconcile some threads:
myListenThread - to listening data from server
myReadStreamThread - to read data from server
System.Threading.Thread - main thread eg. to write data to server
captureThread - to do another things like capturing images from camera
Part of my code:
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
Connect();
Connected = true;
this.myListenThread = new Thread(new ThreadStart(Listen));
this.myListenThread.Start();
}
catch
{
MessageBox.Show("Invalid host! Try again.");
}
}
private void Listen()
{
this.myReadStreamThread = new Thread(new ThreadStart(ReadStream));
this.myReadStreamThread.Start();
while (Connected)
{
if (!myReadClient.Connected)
{
Connect();
}
}
}
private void Connect()
{
IPAddress IP = IPAddress.Parse(textboxIP.Text);
int PORT = Convert.ToInt32(textboxPORT.Text);
this.myReadClient = new TcpClient();
this.myReadClient.Connect(IP, PORT);//SOMETIMES HERE'S AN ERROR
this.myStream = this.myReadClient.GetStream();
Properties.Settings.Default.IP = Convert.ToString(IP);
Properties.Settings.Default.PORT = Convert.ToString(PORT);
Properties.Settings.Default.Save();
}
private void ReadStream()
{
while (true)
{
try
{
this.myReadBuffer = new byte[this.myReadClient.ReceiveBufferSize];
this.myBufferSize = myStream.Read(myReadBuffer, 0, this.myReadClient.ReceiveBufferSize);
if (myBufferSize != 0)
{
this.myString = Encoding.ASCII.GetString(myReadBuffer);
//myDelegate myDel;
//myDel = new myDelegate(Print);
//richtextboxRead.Invoke(myDel);
}
}
catch
{
break;
}
}
}
All is working correct when I'm connecting to server, but when I want to send some string the problem appears because of threads.
I decided to send string, by clicking Button3 and waiting until I receive string "1" from server using while loop:
private void button3_Click(object sender, EventArgs e)
{
this.captureThread = new Thread(new ThreadStart(() => this.newGame()));
this.captureThread.Start();
}
private bool newGame()
{
string command = "12345abc";
if (Connected)
{
WriteStream(command);
}
while (myBufferSize == 0 && myString !="1") { }
Thread.Sleep(2000);
...//doing other things
}
private void WriteStream(string command)
{
Connect();
this.myWriteBuffer = Encoding.ASCII.GetBytes(command);
this.myStream.Write(this.myWriteBuffer, 0, command.Length);
}
And the problem with connection and data send/receive problem appears, when it should write my string "command" - it doesn't react. MyBufferSize is always 0 and myString is always null. Sometimes an Error about connection appears when I click Button3 (assigned in code). I think it is because in captureThread I can't see any data from another threads. How to solve it?

UDP Connection Between Client and Server

Here is the server code of my program this is working, but after it sends data it gets stuck. I need it to be refreshed and ready for sending data again.
Server code:
private void button1_Click(object sender, EventArgs e) {
try {
String text = textBox1.Text;
UdpClient udpc = new UdpClient(text,8899);
IPEndPoint ep = null;
while (true) {
MessageBox.Show("Name: ");
string name = textBox2.Text;
if (name == "") break;
byte[] sdata = Encoding.ASCII.GetBytes(name);
udpc.Send(sdata, sdata.Length);
if (udpc.Receive(ref ep)==null) {
MessageBox.Show("Host not found");
} else {
byte[] rdata = udpc.Receive(ref ep);
string job = Encoding.ASCII.GetString(rdata);
MessageBox.Show(job);
}
}
} catch {
MessageBox.Show("Error Restarting");
}
Client code:
private void button1_Click(object sender, EventArgs e) {
try {
UdpClient subscriber = new UdpClient(8899);
IPAddress addr = IPAddress.Parse("127.0.0.2");
subscriber.JoinMulticastGroup(addr);
IPEndPoint ep = null;
for (int i = 0; i < 1; i++) {
byte[] pdata = subscriber.Receive(ref ep);
string strdata = Encoding.ASCII.GetString(pdata);
MessageBox.Show(strdata);
textBox1.Text = strdata;
pass = strdata;
}
subscriber.DropMulticastGroup(addr);
} catch {
Refresh();
MessageBox.Show("Not Found");
}
}
The Server can send data to one client . I want to send one client at a time. But after sending the data, the server gets stuck.
I need it do refresh and send data again for a client.
If I understood your code, from the server your sending data, then waiting for an answer. In the client, your just getting the data, but not sending anything back. And unless you provide timeout to the socket, it will wait indefinitely until something arrives.
You shouldn't use udpc.Receive() in the main UI thread (inside button1_Click). If you do, your aplication will hang until something arrives. Using a timeout isn't a solution either. The application will just hang until the timeout expires. Instead You must use a multiple threads. You can do so by using BeginReceive instead of Receive or by explicitly creating a new thread and using Receive there. If you google for "asynchronous udp sockets in c#" or something like that, then you will find plenty of examples on how to set it up correctly.
The udpc.Receive() Method on your server side, will Block Until a datagram receive from client.
UDP in not reliable. it means that server doesnt expect any ACK from other side. so you can simply remove this part of code. or if you need to ensure message arrival, run a separate thread for each client as follow:
private void button1_Click(object sender, EventArgs e) {
System.Threading.Thread Server_thread = new Thread(My_Send_Function);
Server_thread .Start();
}
private void My_Send_Function() {
try {
String text = textBox1.Text;
UdpClient udpc = new UdpClient(text,8899);
IPEndPoint ep = null;
while (true) {
MessageBox.Show("Name: ");
string name = textBox2.Text;
if (name == "") break;
byte[] sdata = Encoding.ASCII.GetBytes(name);
udpc.Send(sdata, sdata.Length);
if (udpc.Receive(ref ep)==null) {
MessageBox.Show("Host not found");
} else {
byte[] rdata = udpc.Receive(ref ep);
string job = Encoding.ASCII.GetString(rdata);
MessageBox.Show(job);
}
}
} catch {
MessageBox.Show("Error Restarting");
}
}

Categories