Feedback Form

Socket in Java: TCP Client Programming Mastery

Socket in Java: TCP Client Programming Mastery

Socket in Java क्या है?

Java में Socket एक communication endpoint होता है जो client और server के बीच data exchange करने के लिए use किया जाता है। Simple शब्दों में कहें तो socket एक connection बनाने का तरीका है जिससे दो programs network के ज़रिए आपस में बात कर सकते हैं।

जब हम TCP connection की बात करते हैं, तो Java में socket के माध्यम से हम एक reliable, two-way communication setup करते हैं — यानी data loss नहीं होता और message order में पहुँचता है।

TCP Socket Programming का मतलब

TCP (Transmission Control Protocol) एक connection-oriented protocol है जो data को packet में भेजता है और सुनिश्चित करता है कि सभी packets सही क्रम में पहुँचें। Java में TCP socket का use करके client-server application बनाना बहुत आसान है क्योंकि Java API पहले से ही इसके लिए classes provide करता है जैसे Socket और ServerSocket

TCP Socket Communication कैसे काम करता है?

  • Server पहले एक ServerSocket object बनाता है और किसी specific port पर listen करता है।
  • Client एक Socket object के ज़रिए उस port से connect करता है।
  • Connection establish होने के बाद, दोनों side data भेज और receive कर सकते हैं।
  • Connection तब तक open रहता है जब तक कोई side उसे close नहीं करता।

Socket Class in Java

Socket class Java.net package का हिस्सा है और client-side connection के लिए use होती है। जब client server से connect होता है, तो वह इस class के objects का use करता है।

Important Constructors

ConstructorDescription
Socket(String host, int port)किसी specific server (host) और port से connection बनाता है।
Socket(InetAddress address, int port)IP address के ज़रिए connection बनाता है।

Important Methods

MethodDescription
getInputStream()Server से data पढ़ने के लिए InputStream देता है।
getOutputStream()Server को data भेजने के लिए OutputStream देता है।
close()Socket connection को बंद करता है।
getInetAddress()Connected server का address return करता है।

TCP Client Programming in Java

अब बात करते हैं practical implementation की — यानी कैसे एक TCP Client program बनाया जाता है जो server से connect होकर data send और receive करता है।

Step by Step Explanation

  • Step 1: सबसे पहले socket object create करें और server से connect करें।
  • Step 2: OutputStream के ज़रिए data भेजें।
  • Step 3: InputStream के ज़रिए server से response प्राप्त करें।
  • Step 4: Connection close करें।

Example Code: TCP Client Program

import java.io.*;
import java.net.*;

public class TCPClient {
  public static void main(String[] args) {
    try {
      // Step 1: Connect to server
      Socket socket = new Socket("localhost", 5000);

      // Step 2: Send data to server
      OutputStream output = socket.getOutputStream();
      PrintWriter writer = new PrintWriter(output, true);
      writer.println("Hello Server!");

      // Step 3: Receive response
      InputStream input = socket.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
      System.out.println("Server says: " + reader.readLine());

      // Step 4: Close connection
      socket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

ऊपर दिए गए code में client localhost पर port 5000 से connect होता है और server को message भेजता है। फिर वह server का response पढ़कर console पर print करता है।

Input और Output Streams की भूमिका

Socket communication में InputStream और OutputStream का बहुत बड़ा रोल होता है। Client के पास एक output stream होती है जिससे वह server को data भेजता है और input stream जिससे वह server से data प्राप्त करता है।

InputStream और OutputStream Example

OutputStream out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out, true);
writer.println("Hello Server");

InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String response = reader.readLine();
System.out.println("Response: " + response);

Exception Handling in TCP Client

Socket programming में exceptions का सही तरीके से handle करना बहुत जरूरी है, क्योंकि network connection किसी भी समय fail हो सकता है। Common exceptions जैसे UnknownHostException, IOException और SocketException को catch करना जरूरी है ताकि program crash न हो।

Best Practices for Exception Handling

  • हर IO operation को try-catch block में रखें।
  • Connection establish होने के बाद streams को properly close करें।
  • Timeout set करें ताकि infinite waiting न हो।

TCP Client के Real-world Use Cases

TCP client programming का use कई real-world applications में होता है जैसे:

  • Online chatting applications
  • File transfer systems
  • Remote login systems (SSH, Telnet)
  • Email communication (SMTP, POP3)
  • Database client connections

TCP Client Programming के Important Concepts

1. Connection-Oriented Communication

TCP client-server model में data तब तक transfer होता है जब तक connection established रहता है। यह model reliable होता है क्योंकि इसमें data loss नहीं होता।

2. Reliable Data Transmission

TCP ensure करता है कि हर packet सही क्रम में पहुँचे और अगर कोई packet खो जाता है तो उसे दोबारा भेजा जाता है।

3. Flow Control और Error Checking

TCP automatic flow control और error detection handle करता है जिससे communication smooth और consistent रहता है।

4. Port Numbers

हर TCP connection uniquely identify होता है combination of IP address और port number से।

5. Stream-Oriented Data

TCP में data continuous stream के रूप में भेजा जाता है, यानी bytes का flow जो receiver को sequentially मिलता है।

TCP Socket Programming के Advantages

  • Reliable और ordered data transfer
  • Full duplex communication (दोनों तरफ से data flow)
  • Error detection और recovery support
  • Connection-oriented approach से stability

TCP Client Programming की Limitations

  • Implementation थोड़ा complex होता है।
  • Performance UDP की तुलना में थोड़ी कम होती है।
  • Connection maintain करने में overhead बढ़ जाता है।

Exam/Interview Notes

  • Socket: Network communication endpoint।
  • ServerSocket: Server-side connection establish करता है।
  • Socket class: Client-side connection establish करती है।
  • getInputStream(): Data receive करने के लिए।
  • getOutputStream(): Data send करने के लिए।
  • TCP: Reliable, connection-oriented protocol।
  • Port Number: Connection identify करने के लिए unique number।
  • Full Duplex: दोनों direction में data flow होता है।
  • IOException: Network failure पर throw होती है।
  • Use Case: Chat app, email system, file sharing।

Quick Summary Notes

  • Socket Java में client-server communication का base है।
  • TCP connection reliable और ordered data transfer provide करता है।
  • Client Socket class से connect करता है और getInputStream(), getOutputStream() methods से data exchange करता है।
  • Exception handling जरूरी है ताकि network errors से program crash न हो।
  • TCP client का use real-world apps जैसे chat systems और remote servers में होता है।