Networking in Java


Networking in Java is used for two main tasks: communication with other applications over the network and accessing the URL of an object on the internet.

Source Code

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

public class EchoClient {
    public static void main(String[] args) {
        try (Socket echoSocket = new Socket("taranis", 7);
             PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
             BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                System.out.println("echo: " + in.readLine());
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: taranis.");
            System.exit(1);
        }
    }
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments