0% found this document useful (0 votes)
29 views

Chapter 2

This document discusses Java networking and socket programming. It begins by introducing Java networking and how it allows devices to share resources through socket programming using TCP and UDP protocols. It then defines key Java networking terminology like IP addresses, ports, protocols and sockets. The remainder of the document provides examples of Java socket programming where a client and server can communicate by sending and receiving strings. It demonstrates how to create basic client and server sockets to establish a connection and send/receive data between the two programs.

Uploaded by

Beka Beko
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Chapter 2

This document discusses Java networking and socket programming. It begins by introducing Java networking and how it allows devices to share resources through socket programming using TCP and UDP protocols. It then defines key Java networking terminology like IP addresses, ports, protocols and sockets. The remainder of the document provides examples of Java socket programming where a client and server can communicate by sending and receiving strings. It demonstrates how to create basic client and server sockets to establish a connection and send/receive data between the two programs.

Uploaded by

Beka Beko
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Chapter 2

Java Networking

1
Introduction
Java Networking is a concept of connecting two or more computing
devices together so that we can share resources.
Java socket programming provides facility to share data between
different computing devices.
The java.net package supports two protocols,
TCP: Transmission Control Protocol provides reliable communication
between the sender and receiver. TCP is used along with the Internet Protocol
referred as TCP/IP.
UDP: User Datagram Protocol provides a connection-less protocol service by
allowing packet of data to be transferred along two or more nodes

2
Java Networking Terminology
The widely used Java networking terminologies are given below:
957
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

3
Con…

IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
It is a logical address that can be changed.
Protocol
A protocol is a set of rules basically that is followed for communication. For example:
 TCP
 FTP
 Telnet
 SMTP
 POP etc.

4
Con…
Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between
two applications.
MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network
Interface Controller). A network node can have multiple NIC but each with
unique MAC address.
For example, an ethernet card may have a MAC address of
00:0d:83::b1:c0:8e.

5
Con…

Socket
A socket is an endpoint between two way communications.
Visit next page for Java socket programming.
java.net package
The java.net package can be divided into two sections:
A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers,
Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network
interfaces.
A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier,
URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource
pointed by URLs.
The java.net package provides many classes to deal with networking
applications in Java. A list of these classes is given below:
6
Java Socket Programming
Java Socket programming is used for communication between the
applications running on different JRE.
Java Socket programming can be connection-oriented or connection-
less.
Socket and ServerSocket classes are used for connection-oriented
socket programming and DatagramSocket and DatagramPacket classes
are used for connection-less socket programming.

7
Con…
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
Here, we are going to make one-way client and server communication.
 In this application, client sends a message to the server, server reads the message and prints
it.
Here, two classes are being used: Socket and ServerSocket.
The Socket class is used to communicate client and server.
Through this class, we can read and write message.
The ServerSocket class is used at server-side.
The accept() method of ServerSocket class blocks the console until the client is connected.
After the successful connection of client, it returns the instance of Socket at server-side.

8
9
Con…
Socket class
A socket is simply an endpoint for communications between the
machines.
The Socket class can be used to create a socket.
Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this
socket.
3) public synchronized void close() closes this socket

10
Con…
ServerSocket class
The ServerSocket class can be used to create a server socket. This
object is used to establish communication with the clients.
Important methods

Method Description
1) public Socket accept() returns the socket and establish a connection
between server and client.
2) public synchronized void close() closes the server socket.

11
Example of Java Socket Programming
Creating Server:
To create the server application, we need to create the instance of
ServerSocket class.
Here, we are using 9999 port number for the communication between
the client and server.
You may also choose any other port number.
 The accept() method waits for the client.
If clients connects with the given port number, it returns an instance
of Socket.
ServerSocket ss=new ServerSocket(9999);
Socket s=ss.accept();//establishes connection and waits for the client
12
Con…
Creating Client:
To create the client application, we need to create the instance of
Socket class.
 Here, we need to pass the IP address or hostname of the Server and a
port number.
 Here, we are using "localhost" because our server is running on same
system.
Socket s=new Socket("localhost",6666);

13
Let's see a simple of Java socket programming where client sends a text and server receives and prints it.
• //File: MyClient.java
//File: MyServer.java import java.io.*;
import java.io.*; import java.net.*;
import java.net.*; public class MyClient {
public class MyServer {
public static void main(String[] args) {
public static void main(String[] args){
try{
try{
Socket s=new Socket("localhost",9999);
ServerSocket ss=new ServerSocket(9999);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());dout.writeUTF("Hello Server");
String str=(String)dis.readUTF(); dout.flush();
System.out.println("message= "+str); dout.close();
ss.close(); s.close();
}catch(Exception e){System.out.println(e);} }catch(Exception e){System.out.println(e);}
} }
} }

14
Example of Java Socket Programming (Read-
Write both side)
In this example, client will write first to the server then server will
receive and print the text.
Then server will write to the client and client will receive and print
the text. The step goes on.

15
//File: MyServer.java //File: MyClient.java

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


import java.io.*;
import java.io.*;
class MyClient{
class MyServer{
public static void main(String args[])throws Exception{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
ServerSocket ss=new ServerSocket(3333); DataInputStream din=new DataInputStream(s.getInputStream());
Socket s=ss.accept(); DataOutputStream dout=new DataOutputStream(s.getOutputStream());
DataInputStream din=new DataInputStream(s.getInputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream dout=new DataOutputStream(s.getOutputStream()); String str="",str2="";

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); while(!str.equals("stop")){


str=br.readLine();
String str="",str2="";
dout.writeUTF(str);
while(!str.equals("stop")){
dout.flush();
str=din.readUTF();
str2=din.readUTF();
System.out.println("client says: "+str);
System.out.println("Server says: "+str2);
str2=br.readLine(); }
dout.writeUTF(str2); dout.close();
dout.flush(); s.close();

} }}

din.close();
s.close();
16
ss.close();
Java URL
The Java URL class represents an URL. URL is an acronym for
Uniform Resource Locator. It points to a resource on the World Wide
Web. For example:
https://www.javatpoint.com/java-tutorial

17
Con…
A URL contains many information:
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.javatpoint.com is the server
name.
3. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port
number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.

18
Con…
Constructors of Java URL class
URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler
handler)
Creates an instance of a URL from the given protocol, host, port number, file, and
handler.
URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file
name.
URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.
19
• Commonly used methods of Java URL class
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public String getAuthority() it returns the authority of the URL.
public String toString() it returns the string representation of the
URL.

20
Con….
public String getQuery() it returns the query string of the URL.

public String getDefaultPort() it returns the default port of the URL.

public URLConnection openConnection() it returns the instance of URLConnection i.e.


associated with this URL.

public boolean equals(Object obj) it compares the URL with the given object.

public Object getContent() it returns the content of the URL.


public String getRef() it returns the anchor or reference of the URL.

public URI toURI() it returns a URI of the URL.

21
Example of Java URL class
//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}
}
}
22
example 2

//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("https://www.google.com/search?q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-
8");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("Default Port Number: "+url.getDefaultPort());
System.out.println("Query String: "+url.getQuery());
System.out.println("Path: "+url.getPath());
System.out.println("File: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
23
Java URLConnection Class

The Java URLConnection class


represents a communication link between the URL and the application.
It can be used to read and write data to the specified resource referred by the
URL.
What is the URL?
URL is an abbreviation for Uniform Resource Locator.
An URL is a form of string that helps to find a resource on the World Wide
Web (WWW).
URL has two components:
The protocol required to access the resource.
The location of the resource.
24
Con…
Features of URLConnection class
1. URLConnection is an abstract class. The two subclasses
 HttpURLConnection and
 JarURLConnection
 JarURLConnection makes the connetion between the client Java program and resource on the
internet.
2. With the help of URLConnection class, a user can read and write to and
from any resource referenced by an URL object.
3. Once a connection is established and the Java program has an
URLConnection object, we can use it to read or write or get further
information like content length, etc.

25
url Constructors

Constructor Description
1) protected URLConnection(URL url) It constructs a URL connection to the specified URL.

URLConnection Class Methods

Method Description
void addRequestProperty(String key, String It adds a general request property specified by a key-value pair
value)
void connect() It opens a communications link to the resource referenced by this
URL, if such a connection has not already been established.
boolean getAllowUserInteraction() It returns the value of the allowUserInteraction field for the object.

int getConnectionTimeout() It returns setting for connect timeout.


Object getContent() It retrieves the contents of the URL connection.
Object getContent(Class[] classes) It retrieves the contents of the URL connection.
String getContentEncoding() It returns the value of the content-encoding header field.
26
Con…
int getContentLength() It returns the value of the content-length header field.

long getContentLengthLong() It returns the value of the content-length header field as long.

String getContentType() It returns the value of the date header field.

long getDate() It returns the value of the date header field.

static boolean getDefaultAllowUserInteraction() It returns the default value of the allowUserInteraction field.

boolean getDefaultUseCaches() It returns the default value of an URLConnetion's useCaches flag.

boolean getDoInput() It returns the value of the URLConnection's doInput flag.

27
Con…
boolean getDoInput() It returns the value of the URLConnection's doOutput flag.

long getExpiration() It returns the value of the expires header files.

static FileNameMap getFilenameMap() It loads the filename map from a data file.

String getHeaderField(int n) It returns the value of nth header field

String getHeaderField(String name) It returns the value of the named header field.

long getHeaderFieldDate(String name, long It returns the value of the named field parsed as a number.
Default)
int getHeaderFieldInt(String name, int Default) It returns the value of the named field parsed as a number.

String getHeaderFieldKey(int n) It returns the key for the nth header field.

long getHeaderFieldLong(String name, long It returns the value of the named field parsed as a number.
Default)
28
Con…
Map<String,List<String>> It returns the unmodifiable Map of the header field.
getHeaderFields()
long getIfModifiedSince() It returns the value of the object's ifModifiedSince field.
InputStream getInputStream() It returns an input stream that reads from the open condition.
long getLastModified() It returns the value of the last-modified header field.
OutputStream getOutputStream() It returns an output stream that writes to the connection.
Permission getPermission() It returns a permission object representing the permission
necessary to make the connection represented by the object.
int getReadTimeout() It returns setting for read timeout.

29
Con…
Map<String,List<String>>getRequestProperties() It returns the value of the named general request
property for the connection.
URL getURL() It returns the value of the URLConnection's URL
field.
boolean getUseCaches() It returns the value of the URLConnection's
useCaches field.
Static String guessContentTypeFromName(String It tries to determine the content type of an object,
fname) based on the specified file component of a URL.
static String It tries to determine the type of an input stream
guessContentTypeFromStream(InputStream is) based on the characters at the beginning of the
input stream.
void setAllowUserInteraction(boolean It sets the value of the allowUserInteraction field
allowuserinteraction) of this URLConnection.

30
Con…
Static void It sets the ContentHandlerFactory of an application.
setContentHandlerFactory(ContentHandlerFactory fac)

Static void setDefaultAllowUserInteraction(boolean It sets the default value of the allowUserInteraction


defaultallowuserinteraction) field for all future URLConnection objects to the
specified value.

void steDafaultUseCaches(boolean defaultusecaches) It sets the default value of the useCaches field to the
specified value.

void setDoInput(boolean doinput) It sets the value of the doInput field for this
URLConnection to the specified value.

void setDoOutput(boolean dooutput) It sets the value of the doOutput field for the
URLConnection to the specified value.

31
How to get the object of URLConnection Class

The openConnection() method of the URL class returns the object of


URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}
Displaying Source Code of a Webpage by URLConnecton Class
The URLConnection class provides many methods.
We can display all the data of a webpage by using the getInputStream()
method.
It returns all the data of the specified URL in the stream that can be read and
displayed.

32
Example of Java URLConnection Class
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
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);}
}

33
The Java HttpURLConnection class is http specific URLConnection.
It works for HTTP protocol only.
By the help of HttpURLConnection class, you can retrieve information of any
HTTP URL such as header information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.
HttpURLConnection Class Constructor
Constructor Description
protected HttpURLConnection(URL u) It constructs the instance of HttpURLConnection class.

34
Method Description
void disconnect() It shows that other requests from the server are unlikely in the
near future.
InputStream getErrorStream() It returns the error stream if the connection failed but the server
sent useful data.
Static boolean getFollowRedirects() It returns a boolean value to check whether or not HTTP
redirects should be automatically followed.
String getHeaderField(int n) It returns the value of nth header file.

long getHeaderFieldDate(String name, long Default) It returns the value of the named field parsed as a date.

String getHeaderFieldKey(int n) It returns the key for the nth header file.

boolean getInstanceFollowRedirects() It returns the value of HttpURLConnection's instance


FollowRedirects field.
Permission getPermission() It returns the SocketPermission object representing the
permission to connect to the destination host and port.

35
String getRequestMethod() It gets the request method.
int getResponseCode() It gets the response code from an HTTP response
message.
String getResponseMessage() It gets the response message sent along with the
response code from a server.
void setChunkedStreamingMode(int chunklen) The method is used to enable streaming of a HTTP
request body without internal buffering, when the
content length is not known in advance.
void setFixedLengthStreamingMode(int contentlength) The method is used to enable streaming of a HTTP
request body without internal buffering, when the
content length is known in advance.
void setFixedLengthStreamingMode(long The method is used to enable streaming of a HTTP
contentlength) request body without internal buffering, when the
content length is not known in advance.
static void setFollowRedirects(boolean set) It sets whether HTTP redirects (requests with response
code) should be automatically followed by
HttpURLConnection class.

36
Con…
void setInstanceFollowRedirects(boolean It sets whether HTTP redirects (requests with response code)
followRedirects) should be automatically followed by instance of
HttpURLConnection class.
void setRequestMethod(String method) Sets the method for the URL request, one of: GET POST
HEAD OPTIONS PUT DELETE TRACE are legal, subject to
protocol restrictions.
abstract boolean usingProxy() It shows if the connection is going through a proxy.

Syntax:
1.public URLConnection openConnection()throws IOExceptio
n{}
You can typecast it to HttpURLConnection type as given below.
2.URL url=new URL("http://www.javatpoint.com/java-
tutorial");
3.HttpURLConnection huc=(HttpURLConnection)url.openCon
nection();

37
How to get the object of HttpURLConnection
class
The openConnection() method of URL class returns the object of
URLConnection class.

Syntax:
public URLConnection openConnection()throws IOException{}

You can typecast it to HttpURLConnection type as given below.


URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();

38
Java HttpURLConnection Example
import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
} 39
Java InetAddress class
Java InetAddress class represents an IP address.
 The java.net.InetAddress class provides methods to get the IP of any host name for
example
www.javatpoint.com
 www.google.com
www.facebook.com
An instance of InetAddress represents the IP address with its corresponding host
name.
There are two types of addresses:
Unicast
Multicast.
 The Unicast is an identifier for a single interface whereas Multicast is an identifier
for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful
40
host name resolutions.
Java InetAddress Class Methods
Method Description

public static InetAddress It returns the instance of InetAddress


getByName(String host) throws containing LocalHost IP and name.
UnknownHostException
public static InetAddress getLocalHost() It returns the instance of InetAdddress
throws UnknownHostException containing local host name and address.

public String getHostName() It returns the host name of the IP address.

public String getHostAddress() It returns the IP address in string format.

41
Example of Java InetAddress Class
Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com
website.
//InetDemo.java
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}
42
import java.net.Inet4Address; System.out.print("\nHost Address : " +ip.getHostAddress());
import java.util.Arrays; System.out.print("\
import java.net.InetAddress; nisAnyLocalAddress : " +ip.isAnyLocalAddress());
public class InetDemo2 System.out.print("\
{ nisLinkLocalAddress : " +ip.isLinkLocalAddress());
public static void main(String[] arg) throws E System.out.print("\
xception nisLoopbackAddress : " +ip.isLoopbackAddress());
{ System.out.print("\nisMCGlobal : " +ip.isMCGlobal());
InetAddress ip = Inet4Address.getByName(" System.out.print("\nisMCLinkLocal : " +ip.isMCLinkLocal());
www.javatpoint.com"); System.out.print("\nisMCNodeLocal : " +ip.isMCNodeLocal());
InetAddress ip1[] = InetAddress.getAllByNam System.out.print("\nisMCOrgLocal : " +ip.isMCOrgLocal());
e("www.javatpoint.com");
System.out.print("\nisMCSiteLocal : " +ip.isMCSiteLocal());
byte addr[]={72, 3, 2, 12};
System.out.print("\
System.out.println("ip : "+ip); nisMulticastAddress : " +ip.isMulticastAddress());
System.out.print("\nip1 : "+ip1); System.out.print("\
InetAddress ip2 = InetAddress.getByAddress( nisSiteLocalAddress : " +ip.isSiteLocalAddress());
addr); System.out.print("\nhashCode : " +ip.hashCode());
System.out.print("\nip2 : "+ip2);
System.out.print("\n Is ip1 == ip2 : " +ip.equals(ip2));
System.out.print("\
nAddress : " +Arrays.toString(ip.getAddress()) } 43
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for
connection-less socket programming using the UDP instead of TCP.
Datagram
Datagrams are collection of information sent from one device to another
device via the established network.
 When the datagram is sent to the targeted device, there is no assurance
that it will reach to the target device safely and completely.
 It may get damaged or lost in between.
 Likewise, the receiving device also never know if the datagram received
is damaged or not.
The UDP protocol is used to implement the datagrams in Java.
44
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for
sending and receiving datagram packets.
It is a mechanism used for transmitting datagram packets over network.`
A datagram is basically an information but there is no guarantee of its
content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class
DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it
with the given Port Number.
DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.

45
Java DatagramSocket Class
Method Description
void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.
void close() It closes the datagram socket.
void connect(InetAddress address, It connects the socket to a remote address for the socket.
int port)
void disconnect() It disconnects the socket.
boolean getBroadcast() It tests if SO_BROADCAST is enabled.
DatagramChannel getChannel() It returns the unique DatagramChannel object associated
with the datagram socket.
InetAddress getInetAddress() It returns the address to where the socket is connected.
InetAddress getLocalAddress() It gets the local address to which the socket is connected.
int getLocalPort() It returns the port number on the local host to which the
socket is bound. 46
Con…
SocketAddress getLocalSocketAddress() It returns the address of the endpoint the socket is
bound to.
int getPort() It returns the port number to which the socket is
connected.
int getReceiverBufferSize() It gets the value of the SO_RCVBUF option for
this DatagramSocket that is the buffer size used by
the platform for input on the DatagramSocket.

boolean isClosed() It returns the status of socket i.e. closed or not.

boolean isConnected() It returns the connection state of the socket.

void send(DatagramPacket p) It sends the datagram packet from the socket.

void receive(DatagramPacket p) It receives the datagram packet from the socket.


47
Java DatagramPacket Class
Java DatagramPacket is a message that can be sent or received.
It is a data container.
 If you send multiple packet, it may arrive in any order.
Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class

DatagramPacket(byte[] barr, int length): it creates a datagram packet. This


constructor is used to receive the packets.
DatagramPacket(byte[] barr, int length, InetAddress address, int port): it
creates a datagram packet. This constructor is used to send the packets.

48
Java DatagramPacket Class Methods
Method Description
InetAddress getAddress() It returns the IP address of the machine to which the datagram
is being sent or from which the datagram was received.
byte[] getData() It returns the data buffer.
int getLength() It returns the length of the data to be sent or the length of the
data received.
int getOffset() It returns the offset of the data to be sent or the offset of the
data received.
int getPort() It returns the port number on the remote host to which the
datagram is being sent or from which the datagram was
received.
SocketAddress It gets the SocketAddress (IP address + port number) of the
getSocketAddress() remote host that the packet is being sent to or is coming from.
49
Con…
void setAddress(InetAddress iaddr) It sets the IP address of the machine to which
the datagram is being sent.

void setData(byte[] buff) It sets the data buffer for the packet.

void setLength(int length) It sets the length of the packet.

void setPort(int iport) It sets the port number on the remote host to
which the datagram is being sent.

void setSocketAddress(SocketAddress addr) It sets the SocketAddress (IP address + port


number) of the remote host to which the
datagram is being sent.

50
Example of Sending DatagramPacket by
DatagramSocket
//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}
51
Example of Receiving DatagramPacket by
DatagramSocket
//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
52

You might also like