26 February 2010

Socket Programming

Assalamulaikum wbt..

Firstly, syukur alhamdulillah krn ngn rahmat dri-Nya aku still lgi mmpu menulis kat blog nie..Sedikit petikan kate2 Dr. Danial ms khutbah jumaat td - "Udhulu fi silmi kaaffah" - y mane mksudnye "msuklah kamu kpd Islam scra menyeluruh / total..Oleh krna minggu nie aku struggle wat socket programming, so nk share sikit ar sal bnde nie. Mudah-mudahan korang y bace bnde nie leh expand n get the new knowledge.

"INTRODUCTION"

Let say korang nk wat 1 application cam Yahoo Messanger or Windows Live or Empathy (Ubuntu) y memerlukan extensive message passing between peers. Cara plig kacang n cepat adalah dgn manipulate database n timer sperti mana my teammate Acad wat ms die 2nd year for Widget Community beliau..Ali taip msg, insert kat shared database. Then Babun ade timer, every 3 seconds check database for new incoming msg. If ade y bru, fetch and display it. Same thing when Babun taip msg kpd Ali. Cara nie mmg sng and less complicated since everyone know how to use database (MsSql, MySql, Oracle etc)..But the thing is, frequent database access amat tidak efficient n high possibility for slow data retrieval time when 100 (let say) people access the database at the same time..Contoh laen, KFC ade byk branch kat 1 Malaysia nie. Director nk latest sales data for every branches. Cara plig senang, once again, every branches update shared central database about their latest sales data. Bnde y sama jgak akn berlaku when lot of people access the same shared database at the same time - slow data retrieval or even insertion..

"SOCKET PROGRAMMING"

So, the answer is - Socket Programming. Ape die Socket?? To make simple, aku bg analogi mudah. Socket nie snang nk fhm kalu kite anggap die mcm 1 tunnel y connect between 2 machine..The main thing is mesti kene 1 side jd Server n other side jd Client.

Server should be in "daemon" state - always running or be in infinite loops sbb Server akn wait for any incoming request..For that reason, Server kene ade ip address and port number that it will listen on to. Bind ip address dgn port number, listen then accept incoming connection, thats all..Kire kite create 1 public tunnel la..Simple kn..Client plak xperlu establish port number. Just create socket class, connect with Server's ip address n port number, setel..port number nie penting sbb server ade byk port number. Kite ade reserved port from 1 - 1024, so available port 1025 till 6000++..byk kn..Just imagine kite ade rumah y byk pintu but 1 je alamat rumah, so skg korang nk suh client tue masuk ikut pintu mana.

"NETWORK PROTOCOL - TCP OR UDP ??"

Next major things are type of data packet n internet protocol. Dlm Socket Programming, ade 2 protocol y kite bleh gune, TCP or UDP..Deep explaination bleh tanye Uncle Googlerudin. Briefly, TCP nie connection oriented n UDP conectionless. Analogy mudah (cam bese), TCP nie cam korang call mak kat kmpung. Once korang dail no. tepon, korang kene tgu mak korang agkat tepon dlu bru bleh ckap rite. Thats means in TCP, connection must establish first before data transmision can be done. However in UDP, analogi nye cam korang send SMS kat pakwe. Juz taip then send kat no tepon y berkaitan. Korang xtaw pn SMS tue dh dibaca ker blum, ape y korang tw ialah SMS tue dh delivered (lum tentu pakwe korang bace lg)..In other words, UDP doesn't need established or reliable connection..

So, bile ms nk gune TCP or UDP?? My opinion, use TCP if packets sequence is important or packet size is big (more than 1024 byte), otherwise use UDP instead..Aku bg contoh, application cam Yahoo Messanger gune UDP, since ape je y nk di send, juz string perkataan or file2 kecik. But Internet Download Manager (IDM) kene gune TCP protocol, kalu x, cmana die nk tlog donloadkn muvie korang kat Syok.org y 700 MB tue ye x..

"CODE EXAMPLE"

Finnish theory class, now practical part. Kat bwah nie aku bg sample code dalam Java utk Socket programming using UDP as network protocol

UDP Server:
import java.io.*; 
import java.net.*;

class UDPServer {
public static void main(String args[]) throws Exception
{
try
{
DatagramSocket serverSocket = new DatagramSocket(9876);

byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];

while(true)
{

receiveData = new byte[1024];

DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);

System.out.println ("Waiting for datagram packet");

serverSocket.receive(receivePacket);

String sentence = new String(receivePacket.getData());

InetAddress IPAddress = receivePacket.getAddress();

int port = receivePacket.getPort();

System.out.println ("From: " + IPAddress + ":" + port);
System.out.println ("Message: " + sentence);

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();

DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);

serverSocket.send(sendPacket);

}

}
catch (SocketException ex) {
System.out.println("UDP Port is occupied.");
System.exit(1);
}

}
}

UDP Client:
import java.io.*; 
import java.net.*;

class UDPClient {
public static void main(String args[]) throws Exception
{
try {
String serverHostname = new String ("127.0.0.1");

if (args.length > 0)
serverHostname = args[0];

BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();

InetAddress IPAddress = InetAddress.getByName(serverHostname);
System.out.println ("Attemping to connect to " + IPAddress +
") via UDP port");

byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

System.out.print("Enter Message: ");
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();

System.out.println ("Sending data to " + sendData.length +
" bytes to server.");
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

clientSocket.send(sendPacket);

DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);

System.out.println ("Waiting for return packet");
clientSocket.setSoTimeout(10000);

try {
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());

InetAddress returnIPAddress = receivePacket.getAddress();

int port = receivePacket.getPort();

System.out.println ("From server at: " + returnIPAddress +
":" + port);
System.out.println("Message: " + modifiedSentence);

}
catch (SocketTimeoutException ste)
{
System.out.println ("Timeout Occurred: Packet assumed lost");
}

clientSocket.close();
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
}
}

"CONCLUSION"

Ape y code nie buat adalah sgt simple, client connect with server, send perkataan dlm small letter, server receive n convert to Uppercase n then send blik kat client, thats all..Aku rse ckup kot code kat atas nie, juz nk show how client can communicate with server via Socket Programming..Mula2 mmg pening, tp try ar dlu..mesti best..Bleh gune ape2 java compiler, Netbeans or Eclipse (aku gune Eclipse)..No extra library, juz import java.io n java.net jer..hehe



Welcome to Socket Programming =)





.

8 comments:

  1. wuuuuuuuuuuuu......best r yazid...baru paham...dulu aku igt camni, bnda yg stream, slalunye kene pakai UDP...contoh, kalo kite tgk youtube, kalo lost 2 seconds movie tuh, kite da x dapat tangkap maksud video tuh. Thats y diorang buat check error...kalo UTP plak, contoh kite anta email, kalo lost packet sket, still boleh faham..then, die x buat check error...erk, jap, ape yg aku ngarut ni....hahahaha

    aku pon x paham ape aku tulis....tapi, thanx atas penerangan socket programming tuh....hehehehe..make me clear...crystal clear...wink2

    ReplyDelete
  2. yup..btul2..Anything y memerlukan reliable connection cam video streaming or file downloading mmg kene gune TCP coz ade chekcum support. Utk simple message passing, UDP pn cukup..


    layanzzz

    ReplyDelete
  3. betul la yazid ckp tu azri..
    udp quite simple la..
    eh yazid..caner nk relatekn dgn case yg memula hg citer tu?
    guna socket programming utk reduce connection ke db..sbb klu nk check status order n so on?

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Create connection ke db gune connection string mmg xrse sgt kalu entry dlm db kite less than 10,000. N selain gune Ado.net (cm y korang gne skg) utk select record from db, da bbrape cre len lgi cm Transact/SQL etc..

    Socket ni lbh sesuai gune ms peer-to-peer connection.

    ReplyDelete
  6. men, bahasanya yang bener donk!!!
    kalo inggris yang total sekalian....
    jadi bingung ngebacanya... kayak bahasa sms aja!!!

    ReplyDelete

terima kasih.