Penerimaan data via TCP socket pada c#

Posted: January 13, 2013 by Ujang Carmana in C Sharp, Server, socket programming, TCP Socket

Penerimaan data dilakukan oleh server dengan menerima paket data dari berbagai device pada client. Data yang diterima nantinya akan dimasukan ke dalam sebuah database server. Pada hal ini program penerimaan data menggunakan bahasa pemrograman C# (C shrap). Dengan tujuan utama penggunaan aplikasi ini adalah untuk memudahkan dalam koneksi pada setiap device karena C# merupakan pemrograman berorientasi objek (OOP).

Berikut adalah source code dalam proses penerimaan data dari sebuah device pada client.

using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Threading;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using System.Data;

public class SynchronousSocketListener
{

private const int portNum = 8080;
private static ArrayList ClientSockets;
private static bool ContinueReclaim = true;
private static Thread ThreadReclaim;
public static void StartListening()
{
ClientSockets = new ArrayList();
ThreadReclaim = new Thread(new ThreadStart(Reclaim));
ThreadReclaim.Start();
TcpListener listener = new TcpListener(portNum);
try
{
listener.Start();
int TestingCycle = 3;
int ClientNbr = 0;

// Start listening for connections.
Console.WriteLine(“Waiting for a connection…”);
while (TestingCycle > 0)
{
TcpClient handler = listener.AcceptTcpClient();
if (handler != null)
{
Console.WriteLine(“Client#{0} accepted!”, ++ClientNbr);
// An incoming connection needs to be processed.
lock (ClientSockets.SyncRoot)
{
int i = ClientSockets.Add(new ClientHandler(handler));
((ClientHandler)ClientSockets[i]).Start();
}
// –TestingCycle;
}
else
break;
}
listener.Stop();
ContinueReclaim = false;
ThreadReclaim.Join();

foreach (Object Client in ClientSockets)
{
((ClientHandler)Client).Stop();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine(“\nHit enter to continue…”);
Console.Read();
}

private static void Reclaim()
{
while (ContinueReclaim)
{
lock (ClientSockets.SyncRoot)
{
for (int x = ClientSockets.Count – 1; x >= 0; x–)
{
Object Client = ClientSockets[x];
if (!((ClientHandler)Client).Alive)
{
ClientSockets.Remove(Client);
Console.WriteLine(“A client left”);
}
}
}
Thread.Sleep(200);
}
}

public static int Main(String[] args)
{
StartListening();
return 0;
}
}

class ClientHandler
{

TcpClient ClientSocket;
bool ContinueProcess = false;
Thread ClientThread;

public ClientHandler(TcpClient ClientSocket)
{
this.ClientSocket = ClientSocket;
}

public void Start()
{
ContinueProcess = true;
ClientThread = new Thread(new ThreadStart(Process));
ClientThread.Start();
}

private void Process()
{
string data = null;    // Incoming data from the client.

byte[] bytes;           // Data buffer for incoming data.
if (ClientSocket != null)
{
NetworkStream networkStream = ClientSocket.GetStream();
ClientSocket.ReceiveTimeout = 100; // 1000 miliseconds

while (ContinueProcess)
{
bytes = new byte[ClientSocket.ReceiveBufferSize];
try
{
int BytesRead = networkStream.Read(bytes, 0, (int)ClientSocket.ReceiveBufferSize);
if (BytesRead > 0)
{
data = Encoding.ASCII.GetString(bytes, 0, BytesRead);

// Show the data on the console.
Console.WriteLine(“Text received : {0}”, data);
int panjangdata = data.Length;
Console.WriteLine(“Panjang Data : {0}”, panjangdata);
//Console.Write(panjangdata);

string id_user = “”;
string id_device = “”;
char jenis_ukur ;
string hasil_ukur =””;
string buff = “”;

if ( data.IndexOf(‘*’) < data.IndexOf(‘#’))
{
int limit_awal = data.IndexOf(‘*’);
int limit_akhir = data.IndexOf(‘*’, limit_awal + 1);
//int batas = limit_akhir – limit_awal – 1;

for (int i = limit_awal+1; i < limit_akhir; i++)
{
id_user += data[i];
}
Console.WriteLine(“ID User : {0}”, id_user);
limit_awal = limit_akhir;
limit_akhir = data.IndexOf(‘*’, limit_awal + 1);
for (int i = limit_awal + 1; i < limit_akhir; i++)
{
id_device += data[i];
}
Console.WriteLine(“ID Device : {0}”, id_device);

limit_awal = limit_akhir;
limit_akhir = data.IndexOf(‘#’);
jenis_ukur = data[limit_awal + 1];

for (int i = limit_awal + 2; i < limit_akhir; i++)
{
hasil_ukur += data[i];
}
Console.WriteLine(“Jenis Ukur : {0}”, jenis_ukur);
Console.WriteLine(“Hasil  : {0}”, hasil_ukur);
}

// Echo the data back to the client.
byte[] sendBytes = Encoding.ASCII.GetBytes(data);
networkStream.Write(sendBytes, 0, sendBytes.Length);

if (data == “quit”)
break;
}
}
catch (IOException) { } // Timeout
catch (SocketException)
{
Console.WriteLine(“Conection is broken!”);
break;
}
Thread.Sleep(200);
} // while ( ContinueProcess )
networkStream.Close();
ClientSocket.Close();
}
}  // end Process()

public void Stop()
{
ContinueProcess = false;
if (ClientThread != null && ClientThread.IsAlive)
ClientThread.Join();
}

public bool Alive
{
get
{
return (ClientThread != null && ClientThread.IsAlive);
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s