0% found this document useful (0 votes)
23 views8 pages

Java Networking and Socket Programming

The document provides an overview of networking in Java, detailing concepts such as Java socket programming, TCP and UDP protocols, and important networking terminologies like IP address, port number, and MAC address. It includes examples of Java socket programming for both connection-oriented and connection-less communication, as well as the use of DatagramSocket and DatagramPacket classes. Additionally, it discusses the Java URL and URLConnection classes for handling web resources and data transmission.

Uploaded by

Chaltu Mulatu
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)
23 views8 pages

Java Networking and Socket Programming

The document provides an overview of networking in Java, detailing concepts such as Java socket programming, TCP and UDP protocols, and important networking terminologies like IP address, port number, and MAC address. It includes examples of Java socket programming for both connection-oriented and connection-less communication, as well as the use of DatagramSocket and DatagramPacket classes. Additionally, it discusses the Java URL and URLConnection classes for handling web resources and data transmission.

Uploaded by

Chaltu Mulatu
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

Networking in Java

The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.

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 [Link] package contains a collection of classes and interfaces for
network programming.

The [Link] package provides support for the two common network protocols:

• TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.

• UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets
of data to be transmitted between applications.

Java Networking Terminology

The widely used java networking terminologies are given below`:

1) IP Address: is a unique number assigned to a node of a network e.g. [Link]. It is


composed of octets that range from 0 to 255. It is a logical address that can be changed.

2) Protocol: is a set of rules basically that is followed for communication. For example:TCP,
FTP,Telnet, SMTP, POP etc.

3) Port Number: is used to uniquely identify different applications. It acts as a communication


endpoint between applications. It is associated with the IP address for communication between
two applications.

All the standard protocols and services use the well known port numbers for communication. Some of
them are reserved (numbers 0-1023) and we cannot use these numbers for our own purposes. The port
numbers 1024-49151 are registered (assigned to some well-known services). We can use them, but it is
possible that the required port number is already in use on the machine. The ports with numbers 49152-
65535 are dynamic (or private) ones. We may use them freely for our purposes.

4) 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.

1
5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but


slow. The example of connection-oriented protocol is TCP. But, in connection-less protocol,
acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of
connection-less protocol is UDP.

6) Socket: is an endpoint between two-way communication. An endpoint is a combination of an IP


address and a port number.

Java Socket Programming

Java Socket programming is used for communication between the applications running on
different java runtime environment(JRE). It 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.

The client in socket programming must know two information: IP Address of Server,
and Port number.

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

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
returns the socket and establish a connection between
1) public Socket accept()
server and client.
2) public synchronized void close() closes the server socket.

2
Example of Java Socket Programming

Let's see a simple of java socket programming in which client sends a text and server receives it.

File: [Link]

1. import [Link].*;
2. import [Link].*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=[Link]();//establishes connection
8. DataInputStream dis=new DataInputStream([Link]());
9. String str=(String)[Link]();
10. [Link]("message= "+str);
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }

File: [Link]

1. import [Link].*;
2. import [Link].*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream([Link]());
8. [Link]("Hello Server");
9. [Link]();
10. [Link]();
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }

To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure. After running the client application, a
message will be displayed on the server console.

3
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.

File: [Link]

1. import [Link].*;
2. import [Link].*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=[Link]();
7. DataInputStream din=new DataInputStream([Link]());
8. DataOutputStream dout=new DataOutputStream([Link]());
9. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
10. String str="",str2="";
11. while(![Link]("stop")){
12. str=[Link]();
13. [Link]("client says: "+str);
14. str2=[Link]();
15. [Link](str2);
16. [Link]();
17. }
18. [Link]();
19. [Link]();
20. [Link]();
21. }}

4
File: [Link]

1. import [Link].*;
2. import [Link].*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream([Link]());
7. DataOutputStream dout=new DataOutputStream([Link]());
8. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
9. String str="",str2="";
10. while(![Link]("stop")){
11. str=[Link]();
12. [Link](str);
13. [Link]();
14. str2=[Link]();
15. [Link]("Server says: "+str2);
16. }
17. [Link]();
18. [Link]();
19. }
20. }

DatagramSocket and DatagramPacket (Java Networking)


DatagramSocket class: The DatagramSocket class represents a connection-less socket for
sending and receiving datagram packets. Datagram is basically an information but there is no
guarantee of its content, arrival or arrival time. The DatagramSocket and DatagramPacket
classes are used for connection-less socket programming.
Commonly used Constructors of DatagramSocket class are:
• DatagramSocket() throws SocketException: 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 .

5
DatagramPacket class: The DatagramPacket is message that can be sent or received. If you
send multiple packet, it may arrive in any order. Moreover, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class are:

• 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.
Example of Sending DatagramPacket by DatagramSocket([Link])
import [Link].*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = [Link]("[Link]");
DatagramPacket dp = new DatagramPacket([Link](), [Link](), ip, 3000);
[Link](dp);
[Link]();
} }
Example of Receiving DatagramPacket by DatagramSocket ([Link])

import [Link].*;

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);

[Link](dp);

String str = new String([Link](), 0, [Link]());

[Link](str);

[Link]();

} }

6
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: [Link]

A URL contains many information:

1. Protocol: In this case, https is the protocol.


2. Server name or IP Address: In this case, [Link] is the server name.
3. Port Number: It is an optional attribute. If we write [Link] ,
80 is the port number. If port number is not mentioned in the URL, it returns -1.

Commonly used methods of Java URL class

The [Link] class provides many methods. The important methods of URL class are given
below.

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 URLConnection it returns the instance of URLConnection i.e. associated with this URL.
openConnection()

Example of Java URL class

1. import [Link].*;
2. import [Link].*;
3. public class URLDemo{
4. public static void main(String[] args){
5. try{

5. URL url=new URL("[Link]

6. [Link]("Protocol: "+[Link]());
7. [Link]("Host Name: "+[Link]());
8. [Link]("Port Number: "+[Link]());
9. [Link]("File Name: "+[Link]());
10. }catch(Exception e){[Link](e);}
11. }
12. }

7
Java URLConnection class

The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred by the
URL.

How to get the object of URLConnection class

The openConnection() method of 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. The getInputStream() method returns all the data of the
specified URL in the stream that can be read and displayed.

Example of Java URLConnection class

1. import [Link].*;
2. import [Link].*;
3. public class URLConnectionExample {
4. public static void main(String[] args){
5. try{
6. URL url=new URL("[Link]
7. URLConnection urlcon=[Link]();
8. InputStream stream=[Link]();
9. int i;
10. while((i=[Link]())!=-1){
11. [Link]((char)i);
12. }
13. }catch(Exception e){[Link](e);}
14. }
15. }

You might also like