0% found this document useful (0 votes)
38 views6 pages

Ip Pgms

The document contains code examples for several common Java network programming tasks: 1) An SMTP client program that sends an email with attachments through Gmail's SMTP server using SSL/TLS. 2) A POP3 client program that retrieves and prints emails from a POP3 server. 3) An HTTP client program that makes a GET request to a URL and prints the response. 4) An FTP client-server pair for uploading and downloading files over FTP. 5) A simple chat client-server program that allows text-based communication over UDP. 6) An XML parser program that reads a XML file and extracts user data from it.

Uploaded by

Arun Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views6 pages

Ip Pgms

The document contains code examples for several common Java network programming tasks: 1) An SMTP client program that sends an email with attachments through Gmail's SMTP server using SSL/TLS. 2) A POP3 client program that retrieves and prints emails from a POP3 server. 3) An HTTP client program that makes a GET request to a URL and prints the response. 4) An FTP client-server pair for uploading and downloading files over FTP. 5) A simple chat client-server program that allows text-based communication over UDP. 6) An XML parser program that reads a XML file and extracts user data from it.

Uploaded by

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

SMTP Program

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMailSSL {
public static void main(String[] args) {
String to="[email protected]";//change accordingly
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]","password");//change accordingly
}
});
//compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));//change accordingly
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Hello");
message.setText("Testing.......");
//send message
Transport.send(message);
System.out.println("message sent successfully");
}
catch (MessagingException e)
{
throw new RuntimeException(e);
}

POP3 Program
import
import
import
import
import
import
import
import

java.io.IOException;
java.util.Properties;
javax.mail.Folder;
javax.mail.Message;
javax.mail.MessagingException;
javax.mail.NoSuchProviderException;
javax.mail.Session;
com.sun.mail.pop3.POP3Store;

public class ReceiveMail{


public static void receiveEmail(String pop3Host, String storeType,
String user, String password) {
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);

Session emailSession = Session.getDefaultInstance(properties);


//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {e.printStackTrace();}
catch (MessagingException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
public static void main(String[] args) {
String
String
String
String

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


mailStoreType = "pop3";
username= "[email protected]";
password= "xxxxx";//change accordingly

receiveEmail(host, mailStoreType, username, password);


}
}

Http request Program


import java.net.*;
import java.io.*;
public class URLConnDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL("http://www.amrood.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{
connection = (HttpURLConnection) urlConnection;
}
else
{
System.out.println("Please enter an HTTP URL.");
return;

}
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
}catch(IOException e)
{
e.printStackTrace();
}
}
}

FTP Program
FTP Client:
import java.io.*;
import java.net.*;
public class FTPClient
{
public static void main(String[] args)
{
try
{
Socket client = new Socket("127.0.0.1",10000);
PrintWriter writer = new PrintWriter(client.getOutputStream());
writer.println("f:/demo/HTTP.java");
writer.flush();
InputStreamReader stream = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
reader.close();
}
catch(Exception e)
{
System.out.println("Connection is terminated by the Server");
}}}

FTP Server:
import java.io.*;
import java.net.*;
public class FTPServer

{
public static void main(String[] arg)
{
try
{
ServerSocket server = new ServerSocket(10000);
Socket client;
client= server.accept();
InputStreamReader stream = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String filename = reader.readLine();
PrintWriter writer = new PrintWriter(client.getOutputStream());
FileInputStream fileStream = new FileInputStream(new File(filename));
int ch;
while((ch = fileStream.read()) != -1)
{
writer.write(ch);
writer.flush();
}
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}}}

Simple chat program


Server Side
import java.io.*;
import java.net.*;
class Server
{
public static DatagramSocket serversocket;
public static DatagramPacket dp;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buf[]=new byte[1024];
public static int cport=789,sport=790;
public static void main(String a[])throws IOException
{
serversocket=new DatagramSocket(sport);
dp=new DatagramPacket(buf,buf.length);
dis=new BufferedReader(new InputStreamReader(System.in));
ia=InetAddress.getLocalHost();
System.out.println("Server is waiting for data from client");
while(true)
{
serversocket.receive(dp);
String s=new String(dp.getData(),0,dp.getLength());
System.out.println(s);
}
}
}
Client Side
import java.io.*;
import java.net.*;
class Client

{
public static DatagramSocket clientsocket;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buf[]=new byte[1024];
public static int cport=789,sport=790;
public static void main(String a[])throws IOException
{
clientsocket = new DatagramSocket(cport);
dis=new BufferedReader(new InputStreamReader(System.in));
ia=InetAddress.getLocalHost();
System.out.println("Client is sending data to Server ");
while(true)
{
String str=dis.readLine();
buf=str.getBytes();
clientsocket.send(new DatagramPacket(buf,str.length(),ia,sport));
}
}
}
Parsing XML file
Test.xml
<?xml version="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>
XMLParser1.java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLParser1
{
public void getAllUserNames(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);

if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();
// Print root element of the document
System.out.println("Root element of the document: "+ docEle.getNodeName());
NodeList studentList = docEle.getElementsByTagName("student");
// Print total student elements in document
System.out.println("Total students: " + studentList.getLength());
if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {
Node node = studentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("=====================");
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("name");
System.out.println("Name: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
nodeList = e.getElementsByTagName("grade");
System.out.println("Grade: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
nodeList = e.getElementsByTagName("age");
System.out.println("Age: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
}
}
} else {
System.exit(1);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
XMLParser1 parser = new XMLParser1();
parser.getAllUserNames("test.xml");
}
}

You might also like