المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Multithread UDP listener in C#



C# Programming
09-10-2009, 02:15 AM
Hello to every body.
My name is Christian and i´m not a c# developer (I´m a VFP developer) but some how i manage to built a little UDP server listener app in c#.
I needed to do this becouse I will have several vehicles that send a data via GPRS to the server each minute and the server should be listening and decode the data to store in the database (MySql). There will be hundreds of entries per minute. I Hope that somebady can tell me if my code is multithread or not and if it´s not, how can i implement it. Also, if i need multithread in the database part. The code is this:

using System;
using System.IO;
using System.Net.Sockets;
using System.Net;
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.Xml;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Threading;

namespace httprequest
{
public partial class udp : Form
{
private delegate void SetTextCallback(string text);
private delegate void SetValCallback(int val);

public udp()
{
InitializeComponent();
}

int i;
Socket soc;
const int bufsize = 1024;
byte[] buf = new byte[bufsize];
string szData;

private void button1_Click(object sender, EventArgs e)
{
try
{
i = 0;
IPEndPoint localIP = new IPEndPoint(IPAddress.Parse(this.textBox2.Text),Convert.ToInt32(this.textBox1.Text));
EndPoint epSender = (EndPoint)localIP;
soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
soc.Bind(localIP);
soc.BeginReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
this.button1.Enabled = false;
this.richTextBox1.Text = "Waiting for DataPacket...";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

private void button2_Click(object sender, EventArgs e)
{
this.Close();
}

private void SetText(string text)
{
if(i == 0)
{
this.richTextBox1.Clear();
i = 1;
}
this.richTextBox1.Text += text;
this.richTextBox1.Text += Environment.NewLine;
this.richTextBox1.SelectionStart = richTextBox1.Text.Length - 1;
//this.richTextBox1.ScrollToCaret();

if (text != null)
{
string[] geoValues = text.Split(new char[] { ',' });
if (geoValues.Length > 0 && geoValues.Length == 36)
{
string GeoResponse = geoValues[0].Substring(1, 4);
if (GeoResponse == "unit")
{
string unit = geoValues[0].Substring(6);
string reason = geoValues[7].Substring(7);
string eventid = geoValues[8].Substring(8);
string longitude = geoValues[11].Substring(10);
string latitude = geoValues[12].Substring(9);
string gps_valid = geoValues[14].Substring(10);
string gps_connected = geoValues[15].Substring(14);
string velocity = geoValues[17].Substring(9);
string emergency = geoValues[19].Substring(10);
string door = geoValues[21].Substring(5);
string datetime_actual = geoValues[34].Substring(16);
DateTime UTC = Convert.ToDateTime(datetime_actual);
DateTime LOCAL = UTC.ToLocalTime();
string datetime_actual1 = LOCAL.ToString("yyyy/MM/dd HH:mm:ss");
if (eventid != "0" && reason == "4")
{
conexion con = new conexion();
con.InsertRow(unit, reason, eventid, longitude, latitude, gps_valid, gps_connected, velocity, emergency, door, datetime_actual1);
con.closingcon();
}
}
}
}
}


private void WaitForData()
{
IPEndPoint localIP = new IPEndPoint(IPAddress.Parse(this.textBox2.Text), Convert.ToInt32(this.textBox1.Text));
EndPoint epSender = (EndPoint)localIP;
soc.BeginReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
}

private void OnReceive(IAsyncResult ar)
{
try
{
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
int iRx = 0 ;
iRx = soc.EndReceiveFrom(ar,ref epSender);
char[] chars = new char[iRx+1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buf, 0, iRx, chars, 0);
szData = Encoding.Default.GetString(buf, 0, buf.Length);
string text = szData;
if (this.richTextBox1.InvokeRequired)
{
SetTextCallback f = new SetTextCallback(SetText);
this.Invoke(f, new object[] { text });
}

WaitForData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void udp_Load(object sender, EventArgs e)
{
String strHostName = "";
strHostName = Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
this.textBox2.Text = addr[i].ToString();
}

}

private void button3_Click(object sender, EventArgs e)
{
this.richTextBox1.Clear();
}

}
}