One of the most important features of Java is that it is easy to deal with programs that deal with network , java provided us with classes we can easily create about 90% of programs that deals in the network, without going into details of how transmissions or receptions are done, for example, Messenger Chatting, file-sharing programs , games across the network……
Our topic today will be on (Socket Programming) in fact that we will deal with a socket it is like a tool that allows us to contact, transmit and received ,There are two types of sockets : (TCP Socket,UDP Socket) TCP Socket : There is connection once i call it and whether the process of sending data has done or not the connection will open until i close it. TCP protocol verifies that the message has arrived correctly in the event and did not reach re-send it again UDP Socket : there is no connection except in the case of transmission or reception only, and does not verify the transmission so it’s faster than the TCP for that reason i will not tell much in the theoretical part, lets go with an example using TCP Socket : you can consider it has a simple chat program:
الخطوات الرئيسيه بالنسبه للسيرفر :
1- فتح بورت معين في السيرفر لكي يتصل عن طريقه الكلاينتServerSocket s = new ServerSocket(9000)
لاحظ أننا أخترنا رقم البورت 5000 ، وهناك 65535 بورت أستطيع أستخدام أي واحد منهم ، لكن يفضل دائما الأختيار من البورتات من 1024 الى 65535 ، لأن البورتات من 0الى 1023 تكون محجوزه للخدمات الموجوده في الجهاز .
2- بعد فتح المنفذ ، يكون السيرفر في حاله أستماع Listening أي منتظر أي طلب للأتصال . في حال تم الأتصال به (اي قام كلاينت بالأتصال به) ، فيقوم بعمل accept لهذا الكلاينت ، ويتم عمل accept عن طريق الكائن من نوع Server Socket والذي عن طريقه فتحنا به المنفذ في الخطوة الأولى .
3- الأن عندما أقوم بقبول لهذا الكلاينت ، فالناتج من هذه العمليه هو Socket ، وعن طريقه أستطيع أرسل وأستقبل للكلاينت لكي أقوم بالقرائه من السوكت .
;()InputStream is=client.getInputStream
لاحظ أن الدالة ترجع كائن من نوع InputStream ، وهنا أستطيع استخدام أي كلاس وراث من هذا الكلاس ، مثلا DataInputStream أو Scanner ، أو
ObjectInputStream . Scanner in=new Scanner(is);
4- هنا أصبح Input جاهز للقرائه من السوكت
;()String w=in.next
بالنسبه للخطوات الرئيسيه في الكلاينت فهي : – طلب الأتصال من السيرفر ، ويكون ذلك عن طريق عمل Socket بعنوان السيرفر ، ورقم البورت الذي أريد الأتصال به ، Socket s = new Socket(“127.0.0.1”,9000); بعدما أقوم بطلب الأتصال ، ويقوم السيرفر بعمل accpet لي (الكلاينت) أقوم بتجهيز الStream الكتابه في السوكت ، عكس الخطوه 3 في السيرفر .
PrintWriter pw=new PrintWriter(os);
Nice Article, I’ve Liked it pretty much 😀
Thank you Saad 🙂
حلو اوى طريقه الشرح دى الشرح وبعدين الكود وتوضيح الدوال شكرا ليك على الموضوع