0% found this document useful (0 votes)
16 views22 pages

Chapter-5 Network Programming

Chapter 5 of the document covers Network Programming in Java, focusing on TCP and UDP protocols, socket programming, and client-server communication. It details the use of Java's networking classes, the Java Mail API for sending and receiving emails, and the URLConnection class for handling URL resources. The chapter provides practical examples of creating server and client programs using both TCP and UDP, along with steps for sending and receiving emails in Java.

Uploaded by

14depace
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)
16 views22 pages

Chapter-5 Network Programming

Chapter 5 of the document covers Network Programming in Java, focusing on TCP and UDP protocols, socket programming, and client-server communication. It details the use of Java's networking classes, the Java Mail API for sending and receiving emails, and the URLConnection class for handling URL resources. The chapter provides practical examples of creating server and client programs using both TCP and UDP, along with steps for sending and receiving emails in Java.

Uploaded by

14depace
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/ 22

Network Programming (5 Hrs.

)
BSc. CSIT 7th Semester
Chapter - 5

Er. Jeewan Rai


Computer Engineering (Bachelor)
Master in Information System Engineering (Master)
Contents
5.1. Transmission control Protocol (TCP), User Datagram Protocol (UDP),
Ports, IP Address Network Classes in JDK
Chapter – 5 : Network Programming (5 Hrs.)

5.2. Socket programming using TCP, Socket programming using UDP, Working
Advanced JAVA Programming

with URL’s, Working with URL Connection Class.

5.3. Java Mail API, Sending and Receiving Email

12/10/2023 Er. Jeewan Rai 2


Client/Server Communication
Network-based systems consist of a server ,
client , and a media for communication
Chapter – 5 : Network Programming (5 Hrs.)
Advanced JAVA Programming
TCP and UDP
•TCP is a connection-oriented protocol that provides a
reliable flow of data between two computers. Example
Chapter – 5 : Network Programming (5 Hrs.)

applications that use such services are HTTP, FTP, and


Telnet.
Advanced JAVA Programming

•UDP is a protocol that sends independent packets of data,


called datagrams, from one computer to another with no
guarantees about arrival and sequencing.
Hosts Identification and Service Ports
• Every computer on the Internet is identified by a unique, 4-byte IP address .
• Internet supports name servers that translate these names to IP addresses.
Chapter – 5 : Network Programming (5 Hrs.)

• computers often need to communicate and provide more than one type of
service or to talk to multiple hosts/computers at a time. For example, there
Advanced JAVA Programming

may be multiple ftp sessions, web connections, and chat programs all
running at the same time.
• To distinguish these services, a concept of port s, a logical access point,
represented by a 16-bit number. E.g. 80, 81
• IP address can be thought of as a house address when a letter is sent via
post/snail mail and port number as the name of a specific individual to
whom the letter has to be delivered.
Sockets and Socket-based Communication
•Sockets provide an interface for programming networks
•A socket program written in Java language can
Chapter – 5 : Network Programming (5 Hrs.)

communicate to a program written in non-Java (say C or


C++) socket program.
Advanced JAVA Programming

•A server (program) runs on a specific computer and has a


socket that is bound to a specific port.
•The server listens to the socket for a client to make a
connection request the server accepts the connection
•the server gets a new socket bound to a different port
Establishment of path for two-way
communication between a client and server
Chapter – 5 : Network Programming (5 Hrs.)
Advanced JAVA Programming

A client making connection request to the server

Session established for two way communication


SOCKET PROGRAMMING AND JAVA.NET CLASS
•A socket is an endpoint of a two-way
communication link between two programs
Chapter – 5 : Network Programming (5 Hrs.)

running on the network.


•Socket is bound to a port number so that the TCP
Advanced JAVA Programming

layer can identify the application that data is


ordained to be sent.
•Java provides a set of classes, defined in a package
called java.net, to enable the rapid development of
network applications.
•Key classes, interfaces, and exceptions
TCP/IP SOCKET PROGRAMMING
• The two key classes from the java.net package used in creation of server
and client programs are:
Chapter – 5 : Network Programming (5 Hrs.)

• ServerSocket
• Socket
• A server program creates a
Advanced JAVA Programming

specific type of socket that is used


to listen for client requests
(server socket),
• In the case of a connection
request, the program creates a
new socket through which it will
exchange data with the client using
input and output streams.
•Summarize saying that since TCP requires a connection, it
needs the following APIs on server and client
Chapter – 5 : Network Programming (5 Hrs.)

server : socket(), bind(), listen(), accept(), receive(),


send()
Advanced JAVA Programming

client : socket(), connect(), send(), receive()

•And since UDP is a connectionless protocol, it does not


require connect() on the client and listen() and accept()
on the server
server : socket(), bind(), receive(), send()
client : socket(), send(), receive()
Advanced JAVA Programming
Chapter – 5 : Network Programming (5 Hrs.)
TCP Socket Programming
UDP Socket Programming
Java The steps for creating a simple server program
1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
Chapter – 5 : Network Programming (5 Hrs.)

2. Wait for the Client Request:


Socket client = server.accept();
Advanced JAVA Programming

3. Create I/O streams for communicating to the client


DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(“Hello”);
5. Close socket:
client.close();
The steps for creating a simple client program
1. Create a Socket Object:
Socket client = new Socket(server, port_no);
Chapter – 5 : Network Programming (5 Hrs.)

2. Create I/O streams for communicating with the server.


is = new DataInputStream(client.getInputStream());
Advanced JAVA Programming

os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();
UDP SOCKET PROGRAMMING
• Does not guarantee of delivering packet is accomplished by the UDP
protocol which conveys datagram packets.
Chapter – 5 : Network Programming (5 Hrs.)

• Each message is transferred from source machine to destination based on


Advanced JAVA Programming

information contained within that packet. That means, each packet needs
to have destination address and each packet might be routed differently,
and might arrive in any order. Packet delivery is not guaranteed.

• Java supports datagram communication through the following classes:


✔ DatagramPacket
✔ DatagramSocket
TCP - Java Socket Programming
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
Chapter – 5 : Network Programming (5 Hrs.)

public class MyServer { public class MyClient {


public static void main(String[] args){ public static void main(String[] args) {
try{ try{
Advanced JAVA Programming

ServerSocket ss=new ServerSocket(6666); Socket s=new Socket("localhost",6666);


Socket s=ss.accept();//establishes connection DataOutputStream dout=new DataOutputStream(s.getOutputStream())
DataInputStream dis=new DataInputStream(s.getInputStream());
;
String str=(String)dis.readUTF; dout.writeUTF"Hello Server");
System.out.println("message= "+str); dout.flush();
ss.close(); dout.close();
}catchException e){System.out.println(e);} s.close();
} }catchException e){System.out.println(e);}
} }
} MyClient.jav
MyServer.jav
a
a
12/10/2023 Er. Jeewan Rai 15
UDP- Java Socket Programming
public class UDPClient {
public class UDPServer {
private DatagramSocket udpSocket;
private DatagramSocket udpSocket;
private InetAddress serverAddress;
private int port;
private int port;
public UDPServer(int port) throws SocketException, IOException {
Chapter – 5 : Network Programming (5 Hrs.)

private Scanner scanner;


this.port = port;
private UDPClient(String destinationAddr, int port) throws IOException {
this.udpSocket = new DatagramSocket(this.port);
this.serverAddress = InetAddress.getByName(destinationAddr);
}
this.port = port;
private void listen() throws Exception {
Advanced JAVA Programming

udpSocket = new DatagramSocket(this.port);


System.out.println("-- Running Server at " + InetAddress.getLocalHost() + "--");
scanner = new Scanner(System.in);
String msg;
}
while (true) {
public static void main(String[] args) throws NumberFormatException, IOException {
byte[] buf = new byte[256];
UDPClient sender = new UDPClient(args[0], Integer.parseInt(args[1]));
DatagramPacket packet = new DatagramPacket(buf, buf.length);
System.out.println("-- Running UDP Client at " + InetAddress.getLocalHost() + " --");
// blocks until a packet is received
sender.start();
udpSocket.receive(packet);
}
msg = new String(packet.getData()).trim();
private int start() throws IOException {
System.out.println(
String in;
"Message from " + packet.getAddress().getHostAddress() + ": " + msg);
while (true) {
}
in = scanner.nextLine();
}
DatagramPacket p = new DatagramPacket(
public static void main(String[] args) throws Exception {
in.getBytes(), in.getBytes().length, serverAddress, port);
UDPServer client = new UDPServer(Integer.parseInt(args[0]));
client.listen(); UDPServer.jav this.udpSocket.send(p);
UDPClient.jav
12/10/2023 Er. Jeewan Rai 16
} a }
a
https://www.pegaxchange.com/2018/01/23/simple-udp-server-and-client-socket-java/
Java URLConnection Class
• The Java URLConnection class represents a communication link between
the URL and the application.
Chapter – 5 : Network Programming (5 Hrs.)

• It can be used to read and write data to the specified resource referred by
import java.io.*;
the URL. import java.net.*;
Advanced JAVA Programming

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);}
}
12/10/2023 Er. Jeewan Rai 17
}
Sending Email by Java
• To send emails using Java, you need three things:
a) JavaMail API
Chapter – 5 : Network Programming (5 Hrs.)

b) Java Activation Framework (JAF)


Advanced JAVA Programming

c) Your SMTP server details

• You may download the latest version of both JavaMail API and JAF from the
official website of Java. After successfully downloading these two, extract
them. Add mail.jar , smtp.jar and activation.jar file in your classpath to be
eligible to send emails.

12/10/2023 Er. Jeewan Rai 18


Steps and write a java program to send email

• Create a new session object by calling getDefaultInstance() method and


passing properties as argument to get all of the important properties like
Chapter – 5 : Network Programming (5 Hrs.)

hostname of the SMTP server etc.


Advanced JAVA Programming

• Create a MimeMessage object by passing the session object created in


previous step.

• The final step is to send email using the javax.mail.Transport

12/10/2023 Er. Jeewan Rai 19


Sending Email in Java
// Java program to send email
try
import java.util.*; {
import javax.mail.*; // MimeMessage object.
import javax.mail.internet.*; MimeMessage message = new MimeMessage(session);
Chapter – 5 : Network Programming (5 Hrs.)

import javax.activation.*;
import javax.mail.Session; // Set From Field: adding senders email to from field.
import javax.mail.Transport; message.setFrom(new InternetAddress(sender));

// Set To Field: adding recipient's email to from field.


public class SendEmail message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
Advanced JAVA Programming

{
// Set Subject: subject of the email
public static void main(String [] args) message.setSubject("This is Subject");
{
// email ID of Recipient. // set body of the email.
String recipient = "recipient@gmail.com"; message.setText("This is a test mail");

// email ID of Sender. // Send email.


String sender = "sender@gmail.com"; Transport.send(message);
System.out.println("Mail successfully sent");
// using host as localhost }
String host = "127.0.0.1"; catch (MessagingException mex)
{
// Getting system properties mex.printStackTrace();
Properties properties = System.getProperties(); }
}
// Setting up mail server }
properties.setProperty("mail.smtp.host", host);

// creating session object to get properties


12/10/2023
Session session = Session.getDefaultInstance(properties); Er. Jeewan Rai 20
Receiving Email in Java
public class ReceiveMail{ //4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
public static void receiveEmail(String pop3Host, String storeType, for (int i = 0; i < messages.length; i++) {
String user, String password) { Message message = messages[i];
Chapter – 5 : Network Programming (5 Hrs.)

try { System.out.println("---------------------------------");
//1) get the session object System.out.println("Email Number " + (i + 1));
Properties properties = new Properties(); System.out.println("Subject: " + message.getSubject());
properties.put("mail.pop3.host", pop3Host); System.out.println("From: " + message.getFrom()[0]);
Session emailSession = Session.getDefaultInstance(properties); System.out.println("Text: " + message.getContent().toString());
Advanced JAVA Programming

}
//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = POP3Store) emailSession.getStore(storeType); //5) close the store and folder objects
emailStore.connect(user, password); emailFolder.close(false);
emailStore.close();
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX"); } catch NoSuchProviderException e) {e.printStackTrace();}
emailFolder.open(Folder.READ_ONLY; catch MessagingException e) {e.printStackTrace();}
catch IOException e) {e.printStackTrace();}
}

public static void main(String[] args) {

String host = "mail.javatpoint.com";//change accordingly


String mailStoreType = "pop3";
String username= "sonoojaiswal@javatpoint.com";
String password= "xxxxx";//change accordingly

receiveEmail(host, mailStoreType, username, password);

12/10/2023 } Er. Jeewan Rai 21


}
Advanced JAVA Programming
Chapter – 5 : Network Programming (5 Hrs.)

12/10/2023
Er. Jeewan Rai
The End

22

You might also like