WikiGalaxy

Personalize

Java Networking

Introduction to Java Networking:

Java Networking is a concept of connecting two or more computing devices together to share resources. Java provides a powerful networking library that allows developers to easily create network applications.

Socket Programming:

Socket programming is the fundamental technology behind Java networking. It allows for the communication between applications running on different JREs.


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

public class MyServer {
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(6666);
            Socket s = ss.accept();
            DataInputStream dis = new DataInputStream(s.getInputStream());
            String str = (String)dis.readUTF();
            System.out.println("message= " + str);
            ss.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
    

Client-Side Socket:

A client-side socket is used to connect to a server and send or receive data.


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

public class MyClient {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("localhost", 6666);
            DataOutputStream dout = new DataOutputStream(s.getOutputStream());
            dout.writeUTF("Hello Server");
            dout.flush();
            dout.close();
            s.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
    

DatagramSocket and DatagramPacket:

These classes are used for sending and receiving datagrams, which are self-contained, independent packets of data sent over the network.


import java.net.*;

public class DatagramExample {
    public static void main(String[] args) throws Exception {
        DatagramSocket ds = new DatagramSocket();
        String str = "Hello";
        InetAddress ip = InetAddress.getByName("127.0.0.1");
        DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
        ds.send(dp);
        ds.close();
    }
}
    

URL and URLConnection:

The URL class represents a Uniform Resource Locator, which is a pointer to a resource on the World Wide Web. URLConnection is a communication link between the application and a URL.


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

public class URLConnectionExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.example.com");
            URLConnection urlcon = url.openConnection();
            InputStream stream = urlcon.getInputStream();
            int i;
            while((i = stream.read()) != -1) {
                System.out.print((char)i);
            }
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
    

InetAddress Class:

The InetAddress class is used to represent an IP address. It can be used to resolve hostnames to IP addresses and vice versa.


import java.net.*;

public class InetAddressExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getByName("www.example.com");
            System.out.println("IP Address: " + address.getHostAddress());
            System.out.println("Host Name: " + address.getHostName());
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
    

Multithreaded Server:

A multithreaded server is capable of handling multiple client requests simultaneously by using threads.


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

public class MultiThreadedServer implements Runnable {
    Socket socket;
    MultiThreadedServer(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            String str = (String)dis.readUTF();
            System.out.println("message= " + str);
            socket.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(6666);
            while(true) {
                Socket s = ss.accept();
                new Thread(new MultiThreadedServer(s)).start();
            }
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
    

HTTP Client:

Java provides an HTTP client API to send requests to web servers and receive responses.


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

public class HttpClientExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.example.com");
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            con.disconnect();
            System.out.println(content.toString());
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
    

Proxy Settings:

Java allows you to configure proxy settings for network connections, which can be useful for accessing resources behind a firewall.


import java.net.*;

public class ProxyExample {
    public static void main(String[] args) {
        try {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
            URL url = new URL("http://www.example.com");
            HttpURLConnection con = (HttpURLConnection)url.openConnection(proxy);
            con.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            con.disconnect();
            System.out.println(content.toString());
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
    

Secure Sockets (SSL):

Java provides support for secure sockets through the use of SSL/TLS, allowing for encrypted communication over the network.


import javax.net.ssl.*;
import java.io.*;
import java.net.*;

public class SSLClient {
    public static void main(String[] args) {
        try {
            SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket socket = (SSLSocket) ssf.createSocket("www.example.com", 443);
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            out.write("GET / HTTP/1.1\r\n");
            out.write("Host: www.example.com\r\n");
            out.write("\r\n");
            out.flush();

            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }

            in.close();
            out.close();
            socket.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
    

Conclusion:

Java networking provides a comprehensive set of tools for developing network applications. From basic socket programming to advanced HTTP and SSL connections, Java covers a wide range of networking needs.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025