You are on page 1of 41

1

Samarpan Academy
(Tribhuvan University)
Dhumbarahi, Kathmandu

Faculty of Humanities and Social Sciences

Tribhuvan University

Kirtipur Nepal

Lab Report Of: Network Programming

Semester: Sixth

Submitted By:
Name: Simran Shrestha
Reg No: 6-2-1200-8-2018

Submitted To:
Samarpan Academy
Department of Bachelor in Computer
Application
Dhumbarahi, Kathmandu,
Nepal.
ACKNOWLEDGEMENT

I am obliged to a number of people who helped me to organize this Report and


thankful for their kind opinions, suggestions, and appropriate guidelines. I have
received endless support and guidance in finalizing my project so I would like to
take this opportunity to thank them all.

First and foremost, I would like to express my special thanks to my supervisor Mr.
Rajat Dhakal, who helped me a lot in sharpening my knowledge and completing
this lab report. I am also thankful for his continuous feedback and encouragement
throughout the project.

Secondly, I’m overwhelmed with all the support and guidance that I got from my
friends. They have assisted me from time to time in making this report
satisfactorily complete

Last but not least, I’m thankful to all who have been always encouraging and
helping me to cope with the challenges that I faced during the completion of the
project.

Simran Shrestha
April 2022

2
TABLE OF CONTENTS
ACKNOWLEDGEMENT 1
Write a program to send a basic text from a client to a server. 5
Write a program that prints the address of www.google.com. 7
Write a java program to find hostname from IP address. 8
Find the address of a localhost. 9
Determine whether an IP address is IPV4 or IPV6. 10
Testing characteristics of an IP. 11
Are www.classroom.google.com and mail.google.com same? 13
Write a program that lists all the network interfaces. 14
Are www.w3schools.com and www.w3.org.com are same? 15
Write a program to encode any given strings. 16
Write a program to find out if the given address is legitimate or not. 17
Write a program to process webserver log files. 18
Write a program to construct a URL from a string. 19
Write a program to check which protocol does a virtual machine support? 20
Write a program to construct a relative URL. 21
Write a Program to extract the parts of URI. 22
Write a program to extract all the methods of HttpCookie class. 24
Write a program to download a webpage. 26
Write a program to download an object. 27
Program to implement the CookieStore methods. 28
Write a program to read the value of HttpHeader Fields. 30
Write a program to download a webpage with URL connection. 32
Write a Program to print the entire Http Header. 33
Write a program to implement a concept of Data Conversion. 34
Write a program to send a text over a secure socket. 35
Write a program for UDP client and UDP Server. 36

3
Write a program to multiply two numbers using Rmi. 38

4
1. Write a program to send a basic text from a client to a server.

Client program:

package myclient;
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args){
try{
Socket s = new Socket("localhost",3333);
DataOutputStream dout=new DataOutputStream
(s.getOutputStream());
dout.writeUTF(“Hello! I’m Simran Shrestha. Nice to meet
you.”);
dout.flush();

dout.close();
s.close();
}
catch(Exception e){
System.out.println(e);
}
}
}

Server Program:

package myserver;
import java.net.*;
import java.io.*;
public class MyServer {
public static void main(String[] args) {
try{
ServerSocket ss=new ServerSocket(3333);
Socket s = ss.accept();
DataInputStream dis=new DataInputStream
(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e){
System.out.println(e);

5
}
}
}
}

Output:

6
2. Write a program that prints the address of www.google.com.

package ipaddress;
import java.io.*;
import java.net.*;
public class IpAddress {
public static void main(String[] args) {
try{
InetAddress ip = InetAddress.getByName("www.google.com");
System.out.println("IP Address is:
"+ip.getHostAddress());
}
catch(UnknownHostException ex){
System.out.println("Failed to find the ip");
}
}
}

Output:
IP Address is: 172.217.160.196

7
3. Write a java program to find hostname from IP address.

package ipaddress;
import java.net.InetAddress;
public class HostNameEg {
public static void main(String[] args) throws Exception {

InetAddress address = InetAddress.getByName("152.199.38.98");


System.out.println("Host name is: "+address.getHostName());
System.out.println("Ip address is: "+
address.getHostAddress());

Output:
Host name is: 152.199.38.98
Ip address is: 152.199.38.98

8
4. Find the address of a localhost.

package gethostname;
import java.net.InetAddress;
import java.net.*;
public class GetHostName {
public static void main(String[] args) {
try{
InetAddress add = InetAddress.getLocalHost();
String address = add.getHostAddress();
System.out.println("Ip address of local machine is:"+
address);
}
catch(UnknownHostException e){
System.out.println("Address not found");
}
}
}

Output:
Ip address of local machine is : 192.168.1.22

9
5. Determine whether an IP address is IPV4 or IPV6.

package network programming 6th sem;


import java.net.*;
public class AddressTests{
public static void main(String[] args){
try{
InetAddress ia = InetAddress.getByName(“2001:0db8:85a3:131
9:8a2e:0370:7344");
byte[] address = ia.getAddress();
if (address.length == 4)
System.out.println("This is IPV4");
else if(address.length == 16)
System.out.println("This is IPV6");
}
catch(UnknownHostException ex){
System.out.println(ex);
}
}
}

Output:
This is IPV6

10
6. Testing characteristics of an IP.

package networkprogramming6thsem;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class CharacteristicsIp {
public static void main(String[] args){
try{
InetAddress add = InetAddress.getByName(args[0]);
if(add.isAnyLocalAddress()){
System.out.print(add+ "is an address");
}
if(add.isLoopbackAddress()){
System.out.print(add+ "is loopback address");
}
if (add.isLinkLocalAddress()){
System.out.println(add + " is a link-local address.");
}
else if(add.isSiteLocalAddress()){
System.out.println(add + " is a site-local address.");
}
else{
System.out.println(add + " is a global address.");
}
if (add.isMulticastAddress()){
if (add.isMCGlobal()){
System.out.println(add + " is a global multicast
address.");
}
else if(add.isMCOrgLocal()){
System.out.println(add+ " is an organization wide
multicast address.");
}
else if(add.isMCSiteLocal()){
System.out.println(add + " is a site wide multicast
address.");
}
else if(add.isMCLinkLocal()){
System.out.println(add + " is a subnet wide multicast
address.");
}
else if(add.isMCNodeLocal()) {
System.out.println(add+ " is an interface-local multicast
address.");

11
}
else {
System.out.println(add + " is an unknown multicast
address type.");
}
else {
System.out.println(add + " is a unicast address.");
}
}
catch (UnknownHostException ex) {
System.out.println("Could not resolve " +args[0]);
}
}
}

Output:

12
7. Are www.classroom.google.com and mail.google.com same?

package networkprogramming6thsem;
import java.net.*;
public class Same {
public static void main (String args[]) {
try {
InetAddress add1 =
InetAddress.getByName("mail.google.com");
InetAddress add2 =
InetAddress.getByName("www.classroom.google.com");
if (add1.equals(add2))
System.out.println("mail.google.com is the same as
www.classroom.google.com");
}
else {
System.out.println("mail.google.com is not the same as
www.classroom.google.com");
}
}
catch (UnknownHostException ex) {
System.out.println("Host lookup failed.");
}
}
}

Output:
mail.google.com is not the same as www.classroom.google.com

13
8. Write a program that lists all the network interfaces.

package networkprogramming6thsem;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class NetworkInterfacesList {
public static void main(String[] args) throws Exception {
Enumeration interfaces =
NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni =
(NetworkInterface)interfaces.nextElement();
System.out.println(ni);
}
}
}

Output:

14
9. Are www.w3schools.com and www.w3.org.com are same?

package networkprogramming6thsem;
import java.net.*;
public class URLEquality{
public static void main (String[] args) {
try {
URL url1 = new URL ("http://www.w3schools.com/");
URL url2 = new URL("http://www.w3org.com./");
if (url1.equals(url2)) {
System.out.println(url1+ " is the same as " + url2);
}
else {
System.out.println(url1+ " is not the same as " + url2);
}
}
catch(MalformedURLException ex){
System.err.println(ex);
}
}
}

Output:

15
10. Write a program to encode any given strings.

package networkprogramming6thsem;
import java.io.*;
import java.net.*;
public class EncodeString {
public static void main(String[] args) {
try {
System.out.println(URLEncoder.encode("Network Programming is
in 6th semester.", "UTF-8"));
System.out.println(URLEncoder.encode("This*string*has*asterisk
s", "UTF-8"));
System.out.println(URLEncoder.encode("I%haven't %
completed%my%project%yet", "UTF-8"));
System.out.println(URLEncoder.encode("This+is+very+interesting
+subject", "UTF-8"));

catch (UnsupportedEncodingException ex) {

throw new RuntimeException("Broken VM does not support


UTF-8");

Output:

16
11. Write a program to find out if the given address is legitimate or not.

package networkprogramming6thsem;
import java.net.*;
public class SpamCheck {
public static final String BLACKHOLE = "www.hkhj.com";
public static void main(String[] args) throws
UnknownHostException {
for (String arg: args) {
if (isSpammer(arg)) {
System.out.println(arg + " is a known spammer.");
} else {
System.out.println(arg + " appears legitimate.");
}
}
}
private static boolean isSpammer(String arg) {
try {
InetAddress address = InetAddress.getByName(arg);
byte[] quad = address.getAddress();
String query = BLACKHOLE;
for (byte octet : quad) {
int unsignedByte = octet < 0 ? octet + 256 : octet;
query = unsignedByte + "." + query;
}
InetAddress.getByName(query);
return true;
}
catch (UnknownHostException e) {
return false;
}
}
}
Output:

17
12. Write a program to process webserver log files.

package networkprogramming6thsem;
import java.io.*;
import java.net.*;
public class LogFiles {
public static void main (String[] args){
try{
FileInputStream fin = new FileInputStream("access.log");
InputStreamReader in = new InputStreamReader(fin);
BufferedReader bins = new BufferedReader(in);
for (String entry = bins.readLine();entry!= null;
entry=bins.readLine()){
int index = entry.indexOf('1');
String ip = entry.substring(0,index);
String theRest = entry.substring(index);
System.out.println("Rest Info="+theRest);
try{
InetAddress address = InetAddress.getByName(ip);
System.out.println("IP="+ip);
System.out.println("Host="+address.getHostName());
}
catch(UnknownHostException ex){
System.err.println("Host Is Not Resolved");
}
}
bins.close();
}
catch(IOException ex){
System.out.println("Exception:" +ex);
}
}
}

18
13. Write a program to construct a URL from a string.

package networkprogramming6thsem;
import java.net.MalformedURLException;
import java.net.URL;
public class StringURL {
public static void main (String[] args){
try {
URL u = new
URL("https://www.javatpoint.com/URLConnection-class/");

System.out.println(u.toString());
}
catch (MalformedURLException ex) {
System.err.println(ex);
}
}
}

Output:

19
14. Write a program to check which protocol does a virtual machine
support?

package networkprogramming6thsem;
import java.net.*;
public class ProtocolTester {
public static void main(String[] args){
//http
testProtocol("http://www.geeksforgeeks.com");
//https
testProtocol("https://www.amazon.com");
//ftp
testProtocol("ftp://ibiblio.org/pub/languages/java/");
//smtp
testProtocol("mailto:elharo@ibiblio.org");
//telnet
testProtocol("telnet://dibner.poly.edu/");
//gopher
testProtocol("gopher://gopher.anc.org.za/"); }
private static void testProtocol(String url){
try{
URL u =new URL(url);
System.out.println(u.getProtocol()+" is supported");
}
catch(MalformedURLException ex){
String protocol = url.substring(0, url.indexOf(':'));
System.out.println(protocol+" is not supported");
}
}
}

Output:

20
15. Write a program to construct a relative URL.

package networkprogramming6thsem;
import java.net.*;
public class RelativeURL {
public static void main(String[] args){
try {
URL u1 = new URL("http://www.ibiblio.org/javafaq/index.html");
URL u2 = new URL (u1, "mailinglists.html");
System.out.println(u2.toString());
}
catch (MalformedURLException ex)
{ System.err.println(ex);
}
}
}

Output:

21
16. Write a Program to extract the parts of URI.

package networkprogramming6thsem;
import java.net.*;
public class PartsOfURI {
public static void main(String args[]) {
try {
String uribase = "https://www.javatpoint.com/";
String urirelative = "languages/../java";
String str = "https://www.google.co.in/?gws_rd=ssl#"+""
+ "q=networking+in+java+geeksforgeeks"+""
+"&spf=1496918039682";
URI uriBase = new URI(uribase);
URI uri = URI.create(str);
System.out.println("Base URI = " + uriBase.toString());
URI uriRelative = new URI(urirelative);
System.out.println("Relative URI = " +
uriRelative.toString());
URI uriResolved = uriBase.resolve(uriRelative);
System.out.println("Resolved URI = " +
uriResolved.toString());
URI uriRelativized = uriBase.relativize(uriResolved);
System.out.println("Relativized URI = " +
uriRelativized.toString());
System.out.println(uri.normalize().toString());

System.out.println("Scheme = " + uri.getScheme());

System.out.println("Raw Scheme = " +


uri.getRawSchemeSpecificPart());
System.out.println("Scheme-specific part = " +
uri.getSchemeSpecificPart());
System.out.println("Raw User Info = " +
uri.getRawUserInfo());
System.out.println("User Info = " + uri.getUserInfo());

System.out.println("Authority = " + uri.getAuthority());

System.out.println("Raw Authority = " +


uri.getRawAuthority());
System.out.println("Host = " + uri.getHost());

System.out.println("Port = " + uri.getPath());

22
System.out.println("Raw Path = " + uri.getRawPath());

System.out.println("Path = " + uri.getPath());

System.out.println("Query = " + uri.getQuery());


System.out.println("Raw Query = " + uri.getRawQuery());

System.out.println("Fragment = " + uri.getFragment());

System.out.println("Raw Fragment = " +


uri.getRawFragment());
URI uri2 = new URI(str + "fr");
System.out.println("CompareTo =" + uri.compareTo(uri2));

System.out.println("Equals = " + uri.equals(uri2));

System.out.println("Hashcode : " + uri.hashCode());

System.out.println("toString : " + uri.toString());

System.out.println("toASCIIString : " +
uri.toASCIIString());
}
catch (URISyntaxException ex) {
System.err.println(ex);
}
}
}

Output:

23
24
17. Write a program to extract all the methods of HttpCookie class.

package networkprogramming6thsem;
import java.net.*;
public class HttpCookieEg{
public static void main(String[] args) {
// Constructor to create a new cookie.
HttpCookie cookie = new HttpCookie("Hello", "1");
// setComment() method
cookie.setComment("Just for explanation");
// getComment() method
System.out.println("Comment : " + cookie.getComment());
// setCommentURL() method
cookie.setCommentURL("192.168.1.1");
// getCommentURL() method
System.out.println("CommentURL:"+cookie.getCommentURL());
// setDiscard() method
cookie.setDiscard(true);
// getDiscard() method
System.out.println("Discard : " + cookie.getDiscard());
// setPortlist() method
cookie.setPortlist("1001,8520");
// getPortList() method
System.out.println("Ports: " + cookie.getPortlist());
// setDomain() method
cookie.setDomain(".localhost.com");
// getDomain() method
System.out.println("Domain : " + cookie.getDomain());
// setMaxAge() method
cookie.setMaxAge(3600);
// getMaxAge() method
System.out.println("Max Age : " + cookie.getMaxAge());
// setPath() method
cookie.setPath("192.168.1.1/admin/index.html");
// getPath() method
System.out.println("Path: " + cookie.getPath());
// setSecure() method
cookie.setSecure(true);

25
System.out.println("Secure : " + cookie.getSecure());
// getName() method
System.out.println("Name : " + cookie.getName());
// setValue() method : can be used to modify the value of
cookie.
cookie.setValue("2");
// getvalue() method
System.out.println("Value : " + cookie.getValue());
// setVersion() method
cookie.setVersion(1);
// getVersion() method
System.out.println("Version : " + cookie.getVersion());
// setHttPonly() method
cookie.setHttpOnly(true);
// isHttpOnly() method
System.out.println("HTTP only : " + cookie.isHttpOnly());
// toString() method
System.out.println("toString : " + cookie.toString());
// hashcode() method
System.out.println("Hashcode : " + cookie.hashCode());
}
}

Output:

26
18. Write a program to download a webpage.
import java.io.*;
import java.net.*;
public class SourceViewer{
public static void main (String[] args){
try{
URL url = new URL(https://raijeewan.com.np/);
BufferedReader readr = new
BufferedReader(newInputStreamReader(url.openStream())));
BufferedWriter writer = new BufferedWriter(new
FIleWriter(“Download.html”));
String line;
while((line = readr.readLine())!=null){
writer.write(line);
}
readr.close();
writer.close();
System.out.println(“Successfully Downloaded”);
}
catch(MalformedURLException mue){
System.out.println(“Malformed URL Exception raised”);
}
catch(IOException ie){
System.out.println(“IOException raised”);
}
}
}

Output:

27
19. Write a program to download an object.

package networkprogramming6thsem;
import java.io.*;
import java.net.*;
public class ObjectDownload {
public static void main(String[] args){
if (args.length>0){
try{
URL u = new URL(args[0]);
Object o = u.getContent();
System.out.println("I got a "+o.getClass().getName());
} catch(MalformedURLException ex){
System.err.println(args[0]+"is not a parseable URL");
}
catch(IOException ex){
System.err.println(ex);
}
}
}
}

28
20. Program to implement the CookieStore methods.

package networkprogramming6thsem;
import java.io.*;
import java.net.*;
import java.util.*;
public class CookieStoreMethods {
public static void main(String[] args){

// CookieManager and CookieStore


CookieManager cookieManager = new CookieManager();
CookieStore cookieStore = cookieManager.getCookieStore();
// creating cookies and URI
HttpCookie cookieA = new HttpCookie("First", "1");
HttpCookie cookieB = new HttpCookie("Second", "2");
URI uri = URI.create("https://www.geeksforgeeks.org/");
// Method 1 - add(URI uri, HttpCookie cookie)
cookieStore.add(uri, cookieA);
cookieStore.add(null, cookieB);
System.out.println("Cookies successfully added\n");
// Method 2 - get(URI uri)
List cookiesWithURI = cookieStore.get(uri);
System.out.println("Cookies associated with URI in
CookieStore : "+ cookiesWithURI + "\n");
// Method 3 - getCookies()
List cookieList = cookieStore.getCookies();
System.out.println("Cookies in CookieStore : "
+ cookieList + "\n");
// Method 4 - getURIs()
List uriList = cookieStore.getURIs();
System.out.println("URIs in CookieStore”+uriList);

// Method 5 - remove(URI uri, HttpCookie cookie)


System.out.println("Removal of
cookie:"+cookieStore.remove(uri, cookieA));
List remainingCookieList = cookieStore.getCookies();
System.out.println("Remaining Cookies : " + cookieList +
"\n");
// Method 6 - removeAll()
System.out.println("Removal of all Cookies : "
+ cookieStore.removeAll());
List EmptyCookieList = cookieStore.getCookies();
System.out.println("Empty CookieStore : " + cookieList);
}
}
29
Output:

30
21. Write a program to read the value of HttpHeader Fields.

package networkprogramming6thsem;

import java.io.*;
import java.net.*;
import java.util.*;
public class HeaderFields {
String url = "https://facebook.com";
public static void main(String[] args) throws IOException {
try {
String url = "https://instagram.com";
URL urlObj = new URL(url);
HttpURLConnection httpCon = (HttpURLConnection)
urlObj.openConnection();
int responseCode = httpCon.getResponseCode();
String responseMessage = httpCon.getResponseMessage();
String contentType = httpCon.getContentType();
String contentEncoding = httpCon.getContentEncoding();
int contentLength = httpCon.getContentLength();
long date = httpCon.getDate();
long expiration = httpCon.getExpiration();
long lastModified = httpCon.getLastModified();
System.out.println("Response Code: " + responseCode);
System.out.println("Response Message: " +
responseMessage);
System.out.println("Content Type: " + contentType);
System.out.println("Content Encoding: " +
contentEncoding);
System.out.println("Content Length: " + contentLength);
System.out.println("Date: " + new Date(date));
System.out.println("Expiration: " + new
Date(expiration));
System.out.println("Last Modified: " + new
Date(lastModified));
}
catch (MalformedURLException ex) {
System.err.println(ex);
}
}
}

31
Output:

32
22. Write a program to download a webpage with URL connection.

package networkprogramming6thsem;
import java.io.*;
import java.net.*;
public class Webpage {
public static void main (String[] args) {
try {
URL u = new URL("https://www.facebook.com/");
URLConnection uc = u.openConnection();
InputStream in = uc.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(in);
InputStreamReader reader = new InputStreamReader(buffer);
int c;
while ((c = reader.read()) != -1){
System.out.print((char) c);
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
Output:

33
23. Write a Program to print the entire Http Header.

package networkprogramming6thsem;
import java.io.*; import java.net.*;
public class EntireHttpHeader {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try {
URL u = new URL(args[i]);
URLConnection uc = u.openConnection();
for (int j = 1; ; j++) {
String header = uc.getHeaderField(j);
if (header == null)
break;
System.out.println(uc.getHeaderFieldKey(j)+":”+ header);
}
catch (MalformedURLException ex) {
System.err.println(args[i]+"is not a URL I understand.");
}
catch (IOException ex) {
System.err.println(ex);
}
System.out.println();
}
}
}

34
24. Write a program to implement a concept of Data Conversion.

package networkprogramming6thsem;
import java.net.*;
import java.nio.*;
import java.util.*;
public class DataConversion {
public static void main(String[] args){
int capacity = 8;
try{
ByteBuffer bb = ByteBuffer.allocate(capacity);
bb.asIntBuffer().put(10)
.put(20);
bb.rewind();
System.out.println("Original Byte Buffer: ");
for(int i=1; i<=capacity/4; i++)
System.out.println(bb.getInt() +"");
bb.rewind();
int value = bb.getInt();
System.out.println("\n\nByte value: "+value);
int value1 = bb.getInt();
System.out.println("Next Byte value: "+value1);
int value2 = bb.getInt();
}
catch(BufferUnderflowException e){
System.out.println("\there are fewer than" + "four bytes
remaining in this buffer");
System.out.println("Exception thrown: "+e);
}
}
}

Output:

35
25. Write a program to send a text over a secure socket.

package networkprogramming6thsem;
import java.net.*;
import java.io.*;
import javax.net.ssl.*;
public class SecureSocketExample {
public static void main(String[] args){
try{
SSLSocketFactoryfactory=(SSLSocketFactory)SSLSocketFactor
y.getDefault();
SSLSocket socket =
(SSLSocket)factory.createSocket("www.facebook.com",443);
socket.startHandshake();
PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(
socket.getOutputStream())));
out.println("GET/ HTTP/1.0");
out.println();
out.flush();
if(out.checkError())
System.out.println("SSLSocketClient: java.io.PrintWriet
error");
BufferedReader in = new BufferedReader(new
InputStreamReader(
socket.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!= null)
System.out.println(inputLine);
in.close();
out.close();
socket.close();

}
catch(Exception e ){
e.printStackTrace();
}
}

36
26. Write a program for UDP client and UDP Server.
//UDP Client:

package networkprogramming6thsem;
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String args[] ) throws Exception{
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new
DatagramPacket(sendData,sendData.length,
IPAddress,9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:"+modifiedSentence);
clientSocket.close();
}
}

//UDP Server:
package networkprogramming6thsem;
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPServer {
public static void main(String args[] ) throws Exception{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);

37
String sentence = new String(receivePacket.getData());
System.out.println("RECEIVED:"+sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}

38
27. Write a program to multiply two numbers using Rmi.

package rmimultiplication;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RmiMultiplication extends Remote{
void Multiply(Integer a, Integer b) throws RemoteException;
}

//ImplExample.java
package rmimultiplication;
public class ImplExample implements RmiMultiplication{
ImplExample(){
super();
}
public void Multiply(Integer x , Integer y){
System.out.println("Multiplication = " +(x*y));
}
}

//ServerRmi.java
package rmimultiplication;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ServerRmi extends ImplExample{
public ServerRmi(){}
public static void main (String args[]){
try{
ImplExample obj = new ImplExample();
RmiMultiplication skeleton =
(RmiMultiplication)UnicastRemoteObject.exportObject(obj,0);
Registry registry = LocateRegistry.getRegistry();
registry.bind("RMITest", skeleton);
System.err.println("Server ready");
}
catch(Exception e){
System.err.println("Server exception:"+ e.toString());
e.printStackTrace();
}
}
}

39
//ClientRMI.java
package rmimultiplication;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class ClientRmi {
private ClientRmi(){}
public static void main (String[]args){
try{
Registry registry = LocateRegistry.getRegistry();
RmiMultiplication stub =
(RmiMultiplication)registry.lookup("RMITest");
stub.Multiply(5,10);
}
catch(Exception e){
System.err.println("Client exception:"+e.toString());
e.printStackTrace();
}
}
}

40
41

You might also like