खोज…


वाक्य - विन्यास

  • नया सॉकेट ("लोकलहोस्ट", 1234); // "लोकलहोस्ट" और पोर्ट 1234 के पते पर एक सर्वर से जुड़ता है
  • नया सॉकेटसेवर ("लोकलहोस्ट", 1234); // एक सॉकेट सर्वर बनाता है जो एड्रेस लोकलहोस्ट और पोर्ट 1234 पर नए सॉकेट्स के लिए सुन सकता है
  • socketServer.accept (); // एक नए सॉकेट ऑब्जेक्ट को स्वीकार करता है जिसका उपयोग क्लाइंट के साथ संवाद करने के लिए किया जा सकता है

सॉकेट का उपयोग करके बेसिक क्लाइंट और सर्वर कम्युनिकेशन

सर्वर: प्रारंभ करें, और आने वाले कनेक्शन की प्रतीक्षा करें

//Open a listening "ServerSocket" on port 1234.
ServerSocket serverSocket = new ServerSocket(1234); 

while (true) {
    // Wait for a client connection.
    // Once a client connected, we get a "Socket" object
    // that can be used to send and receive messages to/from the newly 
    // connected client
    Socket clientSocket = serverSocket.accept();            
    
    // Here we'll add the code to handle one specific client.
}

सर्वर: ग्राहकों को संभालना

हम प्रत्येक क्लाइंट को एक अलग थ्रेड में संभालेंगे ताकि एक ही समय में कई क्लाइंट सर्वर के साथ बातचीत कर सकें। यह तकनीक तब तक ठीक काम करती है जब तक क्लाइंट्स की संख्या कम है (<< 1000 क्लाइंट, OS आर्किटेक्चर और प्रत्येक थ्रेड के अपेक्षित लोड के आधार पर)।

new Thread(() -> {
    // Get the socket's InputStream, to read bytes from the socket
    InputStream in = clientSocket.getInputStream();
    // wrap the InputStream in a reader so you can read a String instead of bytes
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(in, StandardCharsets.UTF_8));
    // Read text from the socket and print line by line
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    }).start();

क्लाइंट: सर्वर से कनेक्ट करें और संदेश भेजें

// 127.0.0.1 is the address of the server (this is the localhost address; i.e.
// the address of our own machine)
// 1234 is the port that the server will be listening on
Socket socket = new Socket("127.0.0.1", 1234);

// Write a string into the socket, and flush the buffer
OutputStream outStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(
        new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
writer.println("Hello world!");
writer.flush();

कुर्सियां बंद करना और अपवादों को संभालना

उपरोक्त उदाहरणों ने कुछ चीजों को छोड़ दिया ताकि उन्हें पढ़ने में आसानी हो।

  1. फ़ाइलों और अन्य बाहरी संसाधनों की तरह, यह महत्वपूर्ण है कि हम ओएस को तब बताएं जब हम उनके साथ काम कर रहे हों। जब हम सॉकेट के साथ करते हैं, तो इसे ठीक से बंद करने के लिए socket.close() कॉल करें।

  2. सॉकेट्स I / O (इनपुट / आउटपुट) संचालन को संभालता है जो विभिन्न प्रकार के बाहरी कारकों पर निर्भर करता है। उदाहरण के लिए यदि दूसरा पक्ष अचानक डिस्कनेक्ट हो जाए तो क्या होगा? यदि नेटवर्क त्रुटि हो तो क्या होगा? ये चीजें हमारे नियंत्रण से परे हैं। यही कारण है कि कई सॉकेट संचालन अपवादों को फेंक सकते हैं, विशेष रूप से IOException

ग्राहक के लिए एक अधिक पूर्ण कोड इसलिए कुछ इस तरह होगा:

 // "try-with-resources" will close the socket once we leave its scope
 try (Socket socket = new Socket("127.0.0.1", 1234)) {
     OutputStream outStream = socket.getOutputStream();
     PrintWriter writer = new PrintWriter(
             new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
     writer.println("Hello world!");
     writer.flush();
 } catch (IOException e) {
     //Handle the error
 }

मूल सर्वर और क्लाइंट - पूर्ण उदाहरण

सर्वर:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server {
    public static void main(String args[]) {
        try (ServerSocket serverSocket = new ServerSocket(1234)) {
            while (true) {
                // Wait for a client connection.
                Socket clientSocket = serverSocket.accept();
                
                // Create and start a thread to handle the new client
                new Thread(() -> {
                    try {
                        // Get the socket's InputStream, to read bytes 
                        // from the socket
                        InputStream in = clientSocket.getInputStream();
                        // wrap the InputStream in a reader so you can 
                        // read a String instead of bytes
                        BufferedReader reader = new BufferedReader(
                             new InputStreamReader(in, StandardCharsets.UTF_8));
                        // Read from the socket and print line by line
                        String line;
                        while ((line = reader.readLine()) != null) {
                            System.out.println(line);
                        }
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        // This finally block ensures the socket is closed.
                        // A try-with-resources block cannot be used because
                        // the socket is passed into a thread, so it isn't 
                        // created and closed in the same block
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }

    }
}

ग्राहक:

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Client {
    public static void main(String args[]) {
        try (Socket socket = new Socket("127.0.0.1", 1234)) {
            // We'll reach this code once we've connected to the server
            
            // Write a string into the socket, and flush the buffer
            OutputStream outStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
            writer.println("Hello world!");
            writer.flush();
        } catch (IOException e) {
            // Exception should be handled.
            e.printStackTrace();
        }
    }
}

TrustStore और KeyStore को InputStream से लोड किया जा रहा है

public class TrustLoader {
    
    public static void main(String args[]) {
        try {
                //Gets the inputstream of a a trust store file under ssl/rpgrenadesClient.jks
                //This path refers to the ssl folder in the jar file, in a jar file in the same directory
                //as this jar file, or a different directory in the same directory as the jar file
                InputStream stream = TrustLoader.class.getResourceAsStream("/ssl/rpgrenadesClient.jks");
                //Both trustStores and keyStores are represented by the KeyStore object
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                //The password for the trustStore
                char[] trustStorePassword = "password".toCharArray();
                //This loads the trust store into the object
                trustStore.load(stream, trustStorePassword);
                
                //This is defining the SSLContext so the trust store will be used
                //Getting default SSLContext to edit.
                SSLContext context = SSLContext.getInstance("SSL");
                //TrustMangers hold trust stores, more than one can be added
                TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                //Adds the truststore to the factory
                factory.init(trustStore);
                //This is passed to the SSLContext init method
                TrustManager[] managers = factory.getTrustManagers();
                context.init(null, managers, null);
                //Sets our new SSLContext to be used.
                SSLContext.setDefault(context);
            } catch (KeyStoreException | IOException | NoSuchAlgorithmException 
                    | CertificateException | KeyManagementException ex) {
                //Handle error
                ex.printStackTrace();
            }
        
    }
}

KeyStore शुरू करना एक ही काम करता है, किसी भी शब्द Trust को Key साथ ऑब्जेक्ट नाम में बदलने के अलावा। इसके अतिरिक्त, KeyManager[] सरणी को SSLContext.init के पहले तर्क के लिए पास किया जाना चाहिए। यह SSLContext.init(keyMangers, trustMangers, null)

सॉकेट उदाहरण - एक साधारण सॉकेट का उपयोग करके वेब पेज पढ़ना

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

public class Main {

    public static void main(String[] args) throws IOException {//We don't handle Exceptions in this example 
        //Open a socket to stackoverflow.com, port 80
        Socket socket = new Socket("stackoverflow.com",80);

        //Prepare input, output stream before sending request
        OutputStream outStream = socket.getOutputStream();
        InputStream inStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
        PrintWriter writer = new PrintWriter(new BufferedOutputStream(outStream));

        //Send a basic HTTP header
        writer.print("GET / HTTP/1.1\nHost:stackoverflow.com\n\n");
        writer.flush();

        //Read the response
        System.out.println(readFully(reader));

        //Close the socket
        socket.close();
    }
    
    private static String readFully(Reader in) {
        StringBuilder sb = new StringBuilder();
        int BUFFER_SIZE=1024;
        char[] buffer = new char[BUFFER_SIZE]; // or some other size, 
        int charsRead = 0;
        while ( (charsRead  = rd.read(buffer, 0, BUFFER_SIZE)) != -1) {
          sb.append(buffer, 0, charsRead);
        }
    }
}

आपको HTTP/1.1 200 OK शुरू होने वाली प्रतिक्रिया मिलनी चाहिए, जो सामान्य HTTP प्रतिक्रिया को इंगित करती है, इसके बाद एचटीटीपी के रूप में कच्चे वेब पेज के बाद HTTP हेडर के बाकी हिस्सों को दिखाया जाता है।

ध्यान दें कि समय से पहले ईओएफ अपवाद को रोकने के लिए readFully() विधि महत्वपूर्ण है। वेब पेज की अंतिम पंक्ति में रिटर्न की कमी हो सकती है, लाइन के अंत का संकेत देने के लिए, फिर readLine() शिकायत करेगा, इसलिए किसी को इसे हाथ से पढ़ना चाहिए या अपाचे कॉमन्स-आईओ IOUtils से उपयोगिता विधियों का उपयोग करना चाहिए

यह उदाहरण सॉकेट का उपयोग करके मौजूदा संसाधन से कनेक्ट करने का एक सरल प्रदर्शन के रूप में है, यह वेब पेजों तक पहुंचने का व्यावहारिक तरीका नहीं है। यदि आपको जावा का उपयोग करके किसी वेब पेज तक पहुंचने की आवश्यकता है, तो मौजूदा HTTP क्लाइंट लाइब्रेरी जैसे Apache का HTTP क्लाइंट या Google का HTTP क्लाइंट का उपयोग करना सबसे अच्छा है।

UDP (डेटाग्राम) का उपयोग करके बेसिक क्लाइंट / सर्वर कम्युनिकेशन

Client.java

import java.io.*;
import java.net.*;
    
public class Client{
    public static void main(String [] args) throws IOException{
        DatagramSocket clientSocket = new DatagramSocket(); 
        InetAddress address = InetAddress.getByName(args[0]);

        String ex = "Hello, World!";
        byte[] buf = ex.getBytes();

        DatagramPacket packet = new DatagramPacket(buf,buf.length, address, 4160); 
        clientSocket.send(packet);
    }
}

इस मामले में, हम एक तर्क के माध्यम से सर्वर के पते से गुजरते हैं ( args[0] )। हम जिस पोर्ट का उपयोग कर रहे हैं, वह 4160 है।

Server.java

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

public class Server{
    public static void main(String [] args) throws IOException{
        DatagramSocket serverSocket = new DatagramSocket(4160);

        byte[] rbuf = new byte[256];
        DatagramPacket packet = new DatagramPacket(rbuf, rbuf.length);        
        serverSocket.receive(packet);
        String response = new String(packet.getData());
        System.out.println("Response: " + response);
    }
}

सर्वर-साइड पर, उसी पोर्ट पर एक डेटाग्राम सॉकेट घोषित करें, जिसे हमने अपना संदेश (4160) में भेजा था और प्रतिक्रिया की प्रतीक्षा करें।

मल्टीकास्टिंग

मल्टीकास्टिंग एक प्रकार का डाटाग्राम सॉकेट है। नियमित डेटाग्राम के विपरीत, मल्टीकास्टिंग प्रत्येक क्लाइंट को व्यक्तिगत रूप से नहीं संभालता है बजाय इसे एक आईपी पते पर भेजता है और सभी सब्सक्राइबर क्लाइंट को संदेश मिलेगा।

यहाँ छवि विवरण दर्ज करें

सर्वर साइड के लिए उदाहरण कोड:

public class Server {
    
    private DatagramSocket serverSocket;
    
    private String ip;
    
    private int port;
    
    public Server(String ip, int port) throws SocketException, IOException{
        this.ip = ip;
        this.port = port;
        // socket used to send
        serverSocket = new DatagramSocket();
    }
    
    public void send() throws IOException{
        // make datagram packet
        byte[] message = ("Multicasting...").getBytes();
        DatagramPacket packet = new DatagramPacket(message, message.length, 
            InetAddress.getByName(ip), port);
        // send packet
        serverSocket.send(packet);
    }
    
    public void close(){
        serverSocket.close();
    }
}

ग्राहक पक्ष के लिए उदाहरण कोड:

public class Client {
    
    private MulticastSocket socket;
    
    public Client(String ip, int port) throws IOException {
        
        // important that this is a multicast socket
        socket = new MulticastSocket(port);
        
        // join by ip
        socket.joinGroup(InetAddress.getByName(ip));
    }
    
    public void printMessage() throws IOException{
        // make datagram packet to recieve
        byte[] message = new byte[256];
        DatagramPacket packet = new DatagramPacket(message, message.length);
        
        // recieve the packet
        socket.receive(packet);
        System.out.println(new String(packet.getData()));
    }
    
    public void close(){
        socket.close();
    }
}

सर्वर चलाने के लिए कोड:

public static void main(String[] args) {
    try {
        final String ip = args[0];
        final int port = Integer.parseInt(args[1]);
        Server server = new Server(ip, port);
        server.send();
        server.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

क्लाइंट चलाने के लिए कोड:

public static void main(String[] args) {
    try {
        final String ip = args[0];
        final int port = Integer.parseInt(args[1]);
        Client client = new Client(ip, port);
        client.printMessage();
        client.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

क्लाइंट को पहले चलाएं: क्लाइंट को किसी भी पैकेट को प्राप्त करना शुरू करने से पहले आईपी की सदस्यता लेनी चाहिए। यदि आप सर्वर शुरू करते हैं और send() विधि को कॉल करते हैं, और फिर एक क्लाइंट बनाते हैं (और printMessage() कॉल करें)। कुछ भी नहीं होगा क्योंकि ग्राहक संदेश भेजे जाने के बाद जुड़ा हुआ था।

SSL सत्यापन को अस्थायी रूप से अक्षम करें (परीक्षण प्रयोजनों के लिए)

कभी-कभी एक विकास या परीक्षण वातावरण में, SSL प्रमाणपत्र श्रृंखला पूरी तरह से स्थापित नहीं हो सकती है (अभी तक)।

विकासशील और परीक्षण जारी रखने के लिए, आप एक "ऑल-ट्रस्टिंग" ट्रस्ट मैनेजर स्थापित करके SSL सत्यापन को प्रोग्रामेटिक रूप से बंद कर सकते हैं:

try {
   // Create a trust manager that does not validate certificate chains
   TrustManager[] trustAllCerts = new TrustManager[] {
      new X509TrustManager() {
       public X509Certificate[] getAcceptedIssuers() {
           return null;
       }
       public void checkClientTrusted(X509Certificate[] certs, String authType) {
       }
       public void checkServerTrusted(X509Certificate[] certs, String authType) {
       }
      }
   };

   // Install the all-trusting trust manager
   SSLContext sc = SSLContext.getInstance("SSL");
   sc.init(null, trustAllCerts, new java.security.SecureRandom());
   HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

   // Create all-trusting host name verifier
   HostnameVerifier allHostsValid = new HostnameVerifier() {
       public boolean verify(String hostname, SSLSession session) {
           return true;
       }
   };

   // Install the all-trusting host verifier
   HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
    e.printStackTrace();
}

चैनल का उपयोग करके एक फ़ाइल डाउनलोड करना

यदि फ़ाइल पहले से मौजूद है, तो इसे अधिलेखित कर दिया जाएगा!

String fileName     = "file.zip";                  // name of the file
String urlToGetFrom = "http://www.mywebsite.com/"; // URL to get it from
String pathToSaveTo = "C:\\Users\\user\\";         // where to put it

//If the file already exists, it will be overwritten!
  
//Opening OutputStream to the destination file
try (ReadableByteChannel rbc = 
      Channels.newChannel(new URL(urlToGetFrom + fileName).openStream()) ) {
    try ( FileChannel channel = 
        new FileOutputStream(pathToSaveTo + fileName).getChannel(); ) {
      channel.transferFrom(rbc, 0, Long.MAX_VALUE);
    }
    catch (FileNotFoundException e) { /* Output directory not found */ }
    catch (IOException e)           { /* File IO error */ }
}
catch (MalformedURLException e)     { /* URL is malformed */ }
catch (IOException e)               { /* IO error connecting to website */ }

टिप्पणियाँ

  • पकड़ ब्लॉक खाली मत छोड़ो!
  • त्रुटि के मामले में, जांचें कि क्या दूरस्थ फ़ाइल मौजूद है
  • यह एक अवरुद्ध ऑपरेशन है, बड़ी फ़ाइलों के साथ लंबा समय ले सकता है


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow