Ass 1 Network Prog

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

ZQMS-ARC-REC-002

ASSIGNMENT
COVER
REGION: Mash west SEMESTER: 1 YEAR: 2021

PROGRAMME: Bachelor of Software Engineering BSEH INTAK E: 6

FULL NAME OF STUDEN T: Lovemore Johannes PIN: P1884195L

EMAIL ADDRESS: lojohnes2012@gmail.com

CONTACT TELEPHONE/CELL: 0777993975 ID. NO.: 58-275814A23

COURSE NAME: Network programming COURSE CODE: BITH261

ASSIGNMENT NO. e.g. 1 or 2: 1 STUDENT’S SIGNATURE

DUE DATE: 20 January 2021 SUBMISSION DATE: 13 January 2021

ASSIGNMENT TITLE:

Instructions
Marks will be awarded for good presentation and thoroughness in your approach.
NO marks will be awarded for the entire assignment if any part of it is found to be copied directly
from printed materials or from another student.
Complete this cover and attach it to your assignment. Insert your scanned signature.

Student declaration
I declare that:
 I understand what is meant by plagiarism
 The implications of plagiarism have been explained to me by the institution
 This assignment is all my own work and I have acknowledged any use of the published or
unpublished works of other people.

MARK ER’S COMMEN TS:

OVERALL MARK: MARK ER’S NAME:


MARK ER’S SIGNATURE: DATE:
This study source was downloaded by 100000800936633 from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00

https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
1) Define the following
i) UDP – User Datagram Protocol is a communication protocol used across the internet for
especially time-sensitive transmission such as video playback or DNS lookups.
ii) TCP – Transmission Control Protocol is a networking protocol that allows two
computers to communicate.

2) What is the difference in implementation/ packets of the two protocols?


 TCP is a connection-oriented protocol
 UDP is a connectionless protocol
 TCP uses handshake protocol like SYN, SYN-ACK, ACK
 UDP uses no handshake protocol

3) Write code for client application that is supposed to hack into a remote server listening for
messages on port 2021 and download a file called Secret.txt. Assume that the file is
streamed by the server upon connection.
import Java.net.Socket;
import Java.io.*;
import Java.net.*;
class LojohnesSocket{
public static void main(String[] args){
try{
Socket s = new Socket(“server”,2021);
DataInputStream ts = new DataInputStream(s.getInputStream());
boolean I = true;
while(i){
string str = ts.readline(“Secret.txt”);

if(str = = null) i = false;


else

system.out.println(str);
}
}
catch(IOException e){
system.out.println(“Error occurred” +e);
}
}

QUESTION 2
A) What do you understand by Java Sockets
A Java socket is an end point of a two way communication link between two programs on the
network. A socket is bound to a port number and Java socket is a communication of IP address and
a portwasnumber.
This study source downloaded by 100000800936633 from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00

https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
B) What package would you want to import into a java application to make use of Java sockets
in an application.
 Java.net.*;
 Java.io.*;

C) Write code for a multithreaded server that would echo system time to a telnet client on port
23.

import java.io.BufferedReader;
public class MultithreadedServer{
public static void main(String[] args){
ServerSocket ss = null;
try{
ss = new ServerSocket(23);
ss.setReuseAddress(true);
while(true){
Socket client = ss.accept();
System.out.println(“New client connected” + client.getInetAddress().getHostAddress());
clientHandler clientsock = new clientHandler(client);
new Thread(clientsock).start();
}
}catch (IOException e){
e.printStackTrace();
}finally{
if(ss != null){
try{
ss.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
}
private static class clientHandler implements Runnable{
private final socket clientSocket;
public clientHandler(Socket socket){
this.clientSocket
This study source was downloaded by=100000800936633
socket; from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00

https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
}
public void run(){
printWriter out = null;
BufferedReader in = null;
try{
Out = new printWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
string line;
while((line = in.readline()) != null){
system.out.println(“sent from the client: %s \n”, line);
out.println(line);
}
}catch (IOException e){
e.printStackTrace();
} finally {
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
clientSocket.close();
} catch (IOException e){
e.printStackTrace();
}
}

QUESTION 3
1) Give two ways in which threads can be implemented in Java.
 Extends Thread class: is to create a thread by a new class that extends Thread class and
create an instance of that class. The extending class must override run() method which is the
entry point of new thread.
public class MyThread extends Thread{
public void run(){
system.out.println(“Thread started…..”)
}
public static void main(String[] args){
MyThread t = new MyThread();
This study source was downloaded by 100000800936633 from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00
t.start();
https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
}
}

 Implementing the Runnable Interface: this is the easiest way to create thread. After
implementing runnable interface, the class needs to implement the run() method which is
public void run()
class MyThread implements Runnable{
public void run(){
system.out.println(“Thread started ……”);
}
Public static void main(String[] args){
Mythread t = new MyThread();
Thread m = new Thread(t);
m.start();
}
}

2) What do you understand by serialization and deserialization of objects in Java.


 Serialization is a mechanism of converting the state of an object into a byte stream.
 Deserialization is the reverse process where the byte stream is used to recreate the actual
Java object in memory.
 We implement java.io.serializable interface to make an object serializable
 The objectOutputStream class contains writeObject() method for serializing an object
 The ObjectInputStream class contains readObject() method for deserializing an object.

3) What interface do you have to implement to make your objects serializable.


Public final void writeObject(object obj) throws IOException

4) Create a serializable class called BankAccount with the following fields accountName,
accountNumber, accountType, and balance. You should provide the getters and setters for
the varriables you define and a method called saveToFile() that persists the calling object to
a file called bankaccounts.
import java.io.Serializable;
public class BankAccount implements Serializable{
private string accountName;
private int accountNumber;
private string accountType;
private double balance;
public string ToString(){
return “BankAccount{account name =” +accountName + “, account number =” +accountNumber +
“,account type =” + accountType + “, balance =” + balance +”}”;
}
This study source was downloaded by 100000800936633 from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00
public string getName(){
https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
return accountName;
}
public void setName(String accountName){
this.accountName = accountName;
}
public int getNumber(){
return accountNumber;
}
public void setNumber(int accountNumber){
this.accountNumber = accountNumber;
}
public string getType(){
return accountType;
}
public void setType(string accountType){
this.accountType = accountType;
}
public double getBalance(){
return balance;
}
public void setBalance(double balance){
this.balance = balance;
}
}

QUESTION 4
A) Explain the concept of a layered task with respect to the TCP model.
We always use the concept of layers in our daily life. As an example, let us consider two friends
who communicate through postal email. The process of sending a letter to a friend would be
complex if there were no services available from the post office.
SENDER RECEIVER
The letter is written, put in an Higher layers The letter is picked up,
evelop and dropped in a removed from the envelop and
mailbox. read
↑↑
↓↓
The letter is carried from the Middle layers The letter is carried from the
mailbox to a post office. post office to the mailbox
↑↑
↓↓
The letter is delivered to a Lower layers The letter is delivered from the
carrier by the post office carrier to the post office
→→→→→→→→→→→→→
Parcel is carried from source to destination

B) What is an UnknownHostException.
This is a subclass of IOException, so it is a checked exception. It emerges when you are trying to
connect to a remote host using its host name, but the IP address of that Host cannot be resolved.
This study source was downloaded by 100000800936633 from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00

https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
C) What is a stream.
A stream is a sequence of objects that supports various methods which can be pipelined to produce
the desired results.
D) Explain in your own words, your understanding of persistence objects and serialized
objects.
When we implement persistence objects, we could simply require all classes of persistence objects
to provide a member function that inserts each member variable into a given file stream ( this
process is done by serialized objects).
class persistent
{
public void serialized(fstream);
}
Persistent objects are class used by an entity class. They do not have indices but instead are stored
or retrieved when an entity class makes direct use of them.
Serialized objects they convert state of objects into a byte stream in a way that the byte stream can
be reverted back into a copy of the objects.

E) Why threads are important in network programming.


 A thread is a flow of execution through the process code
 Threads provide a way to improve application performance through parallelism
 It also improves the performance of operating system
 Each thread represents a separate flow of control
 All threads within a process share same global memory

F) What do you understand by synchronisation


 Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
 Synchronisation is used mainly to prevent thread interference and to prevent consistency
problem.
 We have two types of synchronisation which are process synchronization and thread
synchronization.
 We also have two types of thread synchronization which are mutual exclusion and inter-
thread communication.
 Synchronisation is built around an entity known as the lock or monitor. Every object has a
lock associated with it. By convention a thread that needs consistent access to an object’s
field has to aquire the object’s lock before accessing them, and then release the lock when
its done with them.

G) Build a SimpleSleepThread class by implementing Runnable. Create an object Thread and


start the thread. In run method, let the thread sleeps for 10000ms. Display strings before and
after the thread sleeps. Is there any noticeable time difference between the two strings
displayed. Why and why not.
class SimpleSleepThread implements Runnable{
public void run(){
system.out.println(“Thread is now sleeping”);
for(I = 1; i<=5; i++){
try{
Thread.sleep(10000);
}
Catch (interrupted Exception e) system.out.println(e);
}
system.out.println(“Thread is running….”, +i);
} was downloaded by 100000800936633 from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00
This study source
}
https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
public static void main( string[] args){
ThreadSleep ts = new ThreadSleep();
Thread s = new Thread(ts);
s.start();
system.out.println(“Thread ends…..”);
}
}

QUESTION 5
Write a programme that uses the URL class and the OpenStream() method to read and write
interactively the contents of a website. Insert line comments on each line to explain why you put
the code.

//importing java packages


import java.net.*;
import java.io.*;
// creating a class called url browser
public class URLBrowser{
//creating the main method which is the starting point of our program
public static void main(string[] args){
//check to see if number of arguments are passed correctly
if(args.length== 1){
try{
//creating a url object for the url passed on the command line
URL url = new URL(args[0]);
//retrieve the input stream from url
inputStream in = url.OpenStream();
//create a befferred input stream to increase performance
in = new BufferedInputStream(in);
//chain the input stream to a reader
reader reade = new InputStreamReader(in);

//reading and printing what is read on the website


int c;
while((c = reade.read())!= -1){
system.out.println((char)c);
}
This study source was downloaded by 100000800936633 from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00
}catch (malformedURLException mfe){
https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
system.err.println(args[0] + “is not a valid URL”);
}
catch (IOException e){
system.err.println(e);
}
}else{
//handle incorrect number of arguments
system.err.println(“Usage: URLBrowser <valid-url>”);
}
}
}

This study source was downloaded by 100000800936633 from CourseHero.com on 04-12-2023 04:43:17 GMT -05:00

https://www.coursehero.com/file/133753016/ass-1-network-progdoc/
Powered by TCPDF (www.tcpdf.org)

You might also like