[go: up one dir, main page]

0% found this document useful (0 votes)
13 views14 pages

UNIT 5 MEGA NOTES JAVA PROGRAMMING (2)

The document provides an overview of network programming basics, focusing on socket communication in Java, including client and server sockets, proxy servers, and internet addressing. It includes examples of TCP/IP and UDP communication, as well as the usage of URL and URLConnection classes for web resource interaction. Key concepts such as the InetAddress class for IP address handling and the importance of closing sockets after use are also highlighted.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views14 pages

UNIT 5 MEGA NOTES JAVA PROGRAMMING (2)

The document provides an overview of network programming basics, focusing on socket communication in Java, including client and server sockets, proxy servers, and internet addressing. It includes examples of TCP/IP and UDP communication, as well as the usage of URL and URLConnection classes for web resource interaction. Key concepts such as the InetAddress class for IP address handling and the importance of closing sockets after use are also highlighted.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

DiplomaTech Academy

JPR UNIT 5 - Mega Notes


No.1 Academy for Diploma and Engineering in Maharashtra

Unit - V Basics of Network Programming


5.1 Socket Overview: Client/Server , reserved Sockets , proxy servers ,
Internet Addressing
5.2 Java and the Net: The networking classes and interfaces, InetAddress :
Factory Methods , Instance Methods
5.3 TCP/IP Client and Server Sockets, datagram sockets, datagram packets
5.4 The URL Class, URLConnection class

1. Socket Overview

1. A Socket is a connection point between two devices (Client & Server) in a


network.
2. It enables two-way communication over TCP/IP.
3. Java provides Socket class (for client) and ServerSocket class (for server).
4. Client uses socket to request and send data.
5. Server uses ServerSocket to accept client connections.
6. It is used in chat apps, file sharing, online games, etc.
7. Communication happens using InputStream/OutputStream.

2. Client Socket

1. Socket class is used by the client to connect to the server.


2. Requires server IP and port number.
3. Uses getOutputStream() to send data.
4. Uses getInputStream() to receive data.
5. Needs to handle exceptions like IOException.
6. Always close socket after use.
7. Used in real-time client applications.

Syntax:
Socket s = new Socket("localhost", 1234);

Simple Client Example:

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

public class SimpleClient {


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

3. Server Socket

� 7-Line Notes:

1. ServerSocket is used to listen for client connections.


2. Needs a port number (e.g., 1234).
3. Uses accept() method to accept client.
4. Returns a Socket object to communicate with the client.
5. Uses input/output streams for data transfer.
6. Ideal for server-side programs and chat servers.
7. Must close socket and server after use.

Syntax:

ServerSocket ss = new ServerSocket(1234);


Socket s = ss.accept();

Simple Server Example:


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

public class SimpleServer {


public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String msg = dis.readUTF();
System.out.println("Client says: " + msg);
dis.close();
s.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

1. Proxy Servers

1. A proxy server acts as an intermediary between a client and the internet.


2. It hides the client’s IP and filters requests or data.
3. Used for security, anonymity, and network speed control.
4. Java can use proxy settings using Proxy class.
5. You must provide IP and port of proxy.
6. Common proxy types: HTTP, SOCKS.
7. Proxy is useful for bypassing firewalls or geo-blocking.

Syntax:

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy_ip",


port));

Simple Example:

import java.net.*;
import java.io.*;
public class ProxyExample {
public static void main(String[] args) {
try {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new
InetSocketAddress("123.45.67.89", 8080));
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection)
url.openConnection(proxy);
BufferedReader br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
System.out.println("Connected through proxy");
br.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}

2. Internet Addressing

1. Internet Addressing means identifying a device on the internet using an IP.


2. Java uses InetAddress class for addressing.
3. You can get IP from hostname using getByName() method.
4. You can get your own IP using getLocalHost().
5. Used in networking, socket programming, or DNS lookup.
6. IPv4 (e.g., 192.168.1.1) or IPv6 formats are used.
7. Helpful for DNS resolution, ping, or remote connections.

Syntax:

InetAddress ip = InetAddress.getByName("www.google.com");

Simple Example:

import java.net.*;

public class InternetAddressingExample {


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

Output (example):

IP Address: 142.250.195.132
Host Name: www.google.com

5.2 Java and the Net: The Networking Classes and Interfaces

1. InetAddress Class

1. It is used to represent IP addresses in Java.


2. It is in the java.net package.
3. It provides methods to get IP or hostname of a system.
4. Common methods: getByName(), getLocalHost().
5. Used to resolve hostname to IP address and vice versa.
6. Returns an object of InetAddress.
7. Very useful in networking apps to know IP info.

Syntax:

InetAddress ip = InetAddress.getByName("www.google.com");

Simple Example:

import java.net.*;

public class InetAddressExample {


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

2. Socket Class (Client Side)

� 7-Line Notes:

1. Socket class is used for client-side communication.


2. It connects to server using IP and port number.
3. It provides input/output streams to send/receive data.
4. Belongs to java.net package.
5. Important methods: getInputStream(), getOutputStream().
6. Used in TCP communication.
7. Needs a ServerSocket on server to connect.

Syntax:

Socket s = new Socket("localhost", 9999);

Simple Example:

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

public class SocketClient {


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

3. ServerSocket Class (Server Side)

� 7-Line Notes:

1. It is used for server-side socket programming.


2. It listens to incoming connections on a port.
3. Belongs to java.net package.
4. Accepts request using accept() method.
5. Communicates using streams with the client.
6. Used for TCP-based servers.
7. Needs port number to initialize.

Syntax:

ServerSocket ss = new ServerSocket(9999);

Simple Example:

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

public class SocketServer {


public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
String msg = din.readUTF();
System.out.println("Client says: " + msg);
ss.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
InetAddress Class

1. InetAddress class is in the java.net package.


2. It represents IP addresses – both IPv4 & IPv6.
3. Used to get IP address of websites or local machines.
4. Has factory methods like getByName() & getLocalHost().
5. Has instance methods like getHostName() & getHostAddress().
6. Useful for DNS lookups and IP resolution.
7. Commonly used in networking applications.

Factory Methods of InetAddress

� 7-Line Notes:

1. Factory methods are static methods used to get InetAddress objects.


2. getByName(String host) gets IP address of a hostname.
3. getLocalHost() gets the IP of the current machine.
4. These methods throw UnknownHostException.
5. Helps to resolve domain names into IPs.
6. Returns InetAddress object.
7. Commonly used to fetch network info programmatically.

Syntax:

InetAddress ip = InetAddress.getByName("www.google.com");
InetAddress local = InetAddress.getLocalHost();

Simple Example:

import java.net.*;

public class InetAddressFactoryExample {


public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getByName("www.google.com");
InetAddress local = InetAddress.getLocalHost();
System.out.println("Google IP: " + ip);
System.out.println("Local Host IP: " + local);
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}

Output:

Google IP: www.google.com/142.250.195.36


Local Host IP: Aryan-PC/192.168.1.5

Instance Methods of InetAddress

1. Instance methods are called on InetAddress objects.


2. getHostName() returns domain name (like "www.google.com").
3. getHostAddress() returns IP address in string form.
4. toString() returns hostname + IP both.
5. These methods are non-static.
6. Used after calling factory methods.
7. Helpful in displaying network info in apps.

Syntax:

String host = ip.getHostName();


String address = ip.getHostAddress();

Simple Example:

import java.net.*;

public class InetAddressInstanceExample {


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

Host Name: www.google.com


IP Address: 142.250.195.36

1. TCP/IP Client and Server Sockets

1. TCP uses Socket (Client) and ServerSocket (Server) classes.


2. Socket connects to server using IP and port.
3. ServerSocket waits for and accepts client connections.
4. TCP provides reliable, connection-oriented communication.
5. Data is sent using InputStream and OutputStream.
6. TCP is suitable for sending large and ordered data.
7. Always close sockets after communication to free resources.

TCP Server Example:

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

public class TCPServer {


public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept(); // Accept client
DataInputStream dis = new DataInputStream(s.getInputStream());
String msg = dis.readUTF();
System.out.println("Client says: " + msg);
ss.close();
}
}

TCP Client Example:

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

public class TCPClient {


public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 5000); // Connect to server
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello Server");
s.close();
}
}

2. Datagram Sockets (UDP)

� 7-Line Notes:

1. DatagramSocket is used for UDP communication (connectionless).


2. It does not guarantee delivery, order, or error checking.
3. UDP is faster but less reliable than TCP.
4. No connection is established – only sending/receiving packets.
5. We use DatagramSocket and DatagramPacket classes.
6. Common ports used in local programs: 3000, 4000 etc.
7. Best used for small, quick messages.

Syntax:

DatagramSocket ds = new DatagramSocket();

DatagramSocket Example:

import java.net.*;

public class UDPServer {


public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String msg = new String(dp.getData(), 0, dp.getLength());
System.out.println("Client: " + msg);
ds.close();
}
}

. Datagram Packets (UDP)


1. DatagramPacket is used to send or receive data in UDP.
2. Data is wrapped inside a byte array and then packed.
3. For sending: attach message, length, address, and port.
4. For receiving: create a blank packet to store data.
5. Use with DatagramSocket.send() and receive() methods.
6. Can be used in both server and client.
7. Packet size should match the byte array used.

Sending DatagramPacket Example:

import java.net.*;

public class UDPClient {


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

1. URL Class

� 7-Line Notes:

1. The URL class is part of java.net package.


2. It is used to represent a Uniform Resource Locator (web address).
3. Helps in connecting to web resources (like websites, files).
4. Syntax: URL url = new URL("https://example.com");
5. Provides methods like getProtocol(), getHost(), getFile().
6. It throws MalformedURLException if URL is invalid.
7. Mostly used with URLConnection or InputStream to read data.

Syntax:
URL url = new URL("https://www.google.com");

Simple Example:

import java.net.*;

public class URLExample {


public static void main(String[] args) {
try {
URL url = new URL("https://www.google.com");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("File: " + url.getFile());
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}

Output:

Protocol: https
Host: www.google.com
File:

2. URLConnection Class

� 7-Line Notes:

1. URLConnection is used to make a communication link between Java and a web


resource.
2. It is an abstract class from java.net package.
3. Use url.openConnection() to create a URLConnection object.
4. You can read content using InputStream.
5. Methods like getContentType(), getContentLength() are useful.
6. It helps read or write data from the internet.
7. It throws IOException if connection fails.

Syntax:
URLConnection con = url.openConnection();

Simple Example:

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

public class URLConnectionExample {


public static void main(String[] args) {
try {
URL url = new URL("https://www.google.com");
URLConnection con = url.openConnection();
System.out.println("Content Type: " + con.getContentType());
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}

Output:

Content Type: text/html

You might also like