82. WHAT IS GIT ?
• undo on steroids
• Transfer code (allow you to collaborate with others )
• Merge codes
83. WHAT IS GIT ?
• Created by Linus Torvalds, April 2005.
• A command line version control program
• Distributed version control
• Cross platform (including Windows)
• Open source, free
84. Git is a distributed version control system
What is distributed version control?
• “if you're not distributed, you're not worth using” –Linus Torvalds
• No need to connect to central server
• Can work without internet connection
• No single failure point
• Developers can work independently and merge their work later
• Every copy of a git repository can serve either as the server or as a client
• Git tracks changes, not versions
• Branch of little change sets floating around
90. What is repository ?
• Turn the current folder into a git repo by creating a hidden .git folder inside it.
$ git init
• Get the overall status of the git repository (to be explained later)
$ git status
$ git status --short : The short version
• Change default branch name:
$ git config –-global init.defaultBranch main
• Check all of your git config
• $ git config –-list
• $ git config <key name> e.g. $git config user.name
• Local Vs remote repository
91. Important components
In order to save the repo’s state at a certain moment (equivalent to copying it into another directory
so you can bring it back if you break it), we make commits. So each repo consists of many commits.
There is a pointer called HEAD which refers to a certain commit. Git regards this commit as the “last
save”. So it calculates your files’ changes relative to their “image” in this commit. The equivalent of
copying into another directory would be that HEAD refers to the copied folder of the project.
92. *The three state of git files
Working directory:
1. Unchanged (committed)
2. Untracked (All the other types are
technically “tracked”)
3. Modified
4. Deleted
Also called the “Git Index”
or simply “Index”
93. Commands To Move Files Between States
$ git add <filename> : stage modified/untracked file
$ git add . : stage all modified/untracked files
$ git add --all : stage modified/untracked file
$ git commit –m “commit message” : commit the entire staging area
$ git commit : commit the entire staging area ,but write
“extended” commit message in editor.
$ git commit –a –m “commit message” : stage and commit the entire
staging area (does not track untracked files
94. • Checking commit history
$ git log
• Use Enter Key to scroll down when the content does not fit in the terminal.
• Use Q key to exit the scroll area.
• Checking commit history (short version)
$ git log --oneline
95. • Change the editor git commit takes commit messages in
Nano:
$ git config –global core.editor “nano”
VS Code:
$ git config –global core.editor “code --wait”
• Check What git’s current core editor is:
$ git config –global core.editor
$ git config core.editor
96. Undoing things in git
Restoring working directory changes
• Use restore to do all types of restorations
Unstage a staged file:
$ git restore –-staged <filename>
Restore a modified/deleted file (restores it from the stage, NOT from the last commit)
$ git restore <filename>
IDEs like VSCode and Intellij have git extensions that simplify the restoration
process
index head
Working
tree
index
97. Undoing things in git
Restoring working directory changes
$ git restore –-staged <filename>
Working directory
stage
head
98. Undoing things in git
Restoring working directory changes
$ git restore <filename>
Working Dir
stage
head
99. Undoing things in git
Restoring working directory changes
• Use restore to do all types of restorations
Do both of the previous ones:
$ git restore –-staged --worktree <filename>
Head
Working Dir
index
100. Undoing things in git
Undoing Commits
• Each commit is linked to the previous, parent commit. The differences made to
the files between the two commits can easily be calculated by Git.
• Use revert to undo the changes made in a specific commit
$ git revert <ref>
<ref> can be a commit hash (read from git log), or other things which we
do not yet cover.
Note that git revert undoes the changes in exactly the commit specified
and does not work if you want to undo several commits at once
An example will be covered in Project 2
101. What is tag?
Tag types:
1. Annotated: hold information about the author, date created, message,
etc.
2. Lighweight: Only holds info about the commit it’s pointing to.
• Creating and deleting Tags:
$ git tag <tag name>
Creates a lightweight tag on the most recent commit (HEAD) with the specified name
$ git tag <tag name> <commit hash>
Creates a lightweight tag on any commit (specified by hash) with the specified name
$ git tag -a <tag name> -m “tag message”
Creates an annotated tag on the most recent commit (HEAD)with the specified message
and name.
$ git tag -a <tag name> -m “tag message” <commit hash>
Creates an annotated tag on the hash-specified commit with the specified message and
name.
$ git tag -d <tag name>
Deletes a tag locally.
102. • Reading tags
$ git tag
Lists the names of all tags
$ git show <tag name>
Show all the data the tag holds (including commit, message, author, date, etc.)
• Pushing tags : git push origin does NOT push tags
$ git push origin <tag name>
Push the specified tag
$ git push origin --tags
Push all tags
$ git push origin --delete <tag name>
Delete tag from origin (git push does not sync tags)
• Checking out tags
$ git checkout <tag name>
Check out the tag’s commit
103. Git ignore
• Creating .gitignore
$ touch .gitignore
Create the .gitignore file
You can use the wildcard * in your .gitignore directives:
*.txt => ignores all txt files (in ANY directory)
You can ignore entire directories:
hello/ => ignores the contents of hello/ directory ANYWHERE in the repo
/hello/ => ignores the contents of hello/ directory ONLY in the root
To prevent .gitignore’s recursive behavior, you can create .gitignores INSIDE of
directories. The rules specified in those will not apply to parent directories.
List of complete gitignore rules can be found here
107. Git Stores “Snapshots” of the files in each commit
But it’s also easy for
Git to see the changes
between any two commits
108. Git stores commits as a DAG (a directed acyclic graph) in which each commit “points” to its parent commit(s).
Its structure is very similar to linked lists.
Git branches, and tags (and in specific cases HEAD) are references (pointers) to certain commits in the history
Head, branches, and tags
simply “point to commits”
and also hold some
metadata
Last commit
109. As we have already mentioned,
branches are simply “pointers to
commits”. When you make the
first commit in your repository, a
default branch, (names master
or main) is automatically
created and points to the
commit you made.
Master here is a
branch: it points to
the commit with the
hash f30ab
110. Branch Commands
$ git branch
List all branches. Puts a * beside the branch that HEAD currently points to. If HEAD
is detached, will print the commit hash that HEAD points to.
$ git branch <branch name>
Creates a new branch with the given name to point to whatever commit HEAD is
pointing to.
$ git checkout -b <branch name> <commit hash>
Checks out the given commit and also creates a new branch with the given
name to point to it (the HEAD will point to the newly created branch, NOT the
commit, so it will not be detached)
$ git branch –d <branch name>
Deletes the given branch name.
$ git log --all
Show commits and branches and tags for ALL branches, not just the current
one’s
111. What are branches for?
• Better understanding reset: we have introduced used git reset
here. Git reset is a simple git checkout with the difference that if
HEAD is in normal state, the HEAD won’t be updated to point to
the specified commit, but the branch that HEAD is pointing to
will be updated to point to the specified commit
1 2
1 2
1 2
head
master
head master
head
master
113. merging
$ git merge <branch name>
Merges <branch name> “into” whatever branch HEAD is pointing to.
There are 2 types of merging:
1. Fast-Forward Merge
2. Three-Headed Merge
We will first consider the simpler case: fast-forward merge
114. c2
c1
If HEAD is on branch B1 pointing to commit C1 and there is a branch B2 that points to
commit C2 such that C1 is an ancestor of C2 (meaning C1 was turned into C2 through a
series of commits):
Then calling the command
$ git merge B2
Will result in a fast-forward merge. In this type of merge, the branch that the head points to will simply be
updated to point to the same commit as the branch that has been merged into it (in this case B2) See the
result on the next page
B1 head B2
Earliest commit Most recent commit
merging
118. Suppose you have created a branch and have made a few commits to it. Meanwhile, the
master branch has also advanced by a few commits (maybe another developer committed
to master or you merged another branch into it.) Your repo will look like this:
A
B Master
HEAD
Branch
119. Conflict
If you make a mistake in the conflict resolution process and want to undo all
changes you made in the process of merging, use:
$ git merge --abort
General conflict
Note that merging is not the only place you will encounter conflicts. We will see
later on that conflicts arise when we are pulling from remotes as well.
Merge conflicts are not based on line numbers: Git is pretty smart about
comparing files and changes. It is incorrect to think that the only way git
compares to see if two branches have a merge conflict is by comparing their
changes to identical line numbers in files. The Project on the next page will
illuminate this concept.
120. Gitignore
• Blank lines are ignored • Lines starting with # are ignored (comments)
• Wildcards are used!
• *.file → All files withe .file extention
• !name.file → ! specifies a negation or exception. All files withe .file
extention, except name.file
Note: ignore large files, passwords, unnecessary files, etc.
121. GitHub
• remote: where should I upload my git projects
git remote add origin <link of repo> Find repo link on GitHub page
• push: the act of uploading the git project
git push origin master Master → any other branch
• clone: download the whole git project
git clone <repo link>
• pull: check for updates in the remote git
git pull origin master • Fetch and merge! • pull = fetch + merge
122.
123. Revert and reset
• revert vs. reset
• Revert: take a previous commit and add it as a new commit, keeping the log intact.
• Reset: move back to a previous commit, discarding any changes made after that commit.
• git revert [commit_id or hash]
• git reset --hard [commit_hash]
• we can find commit hash from : git log --oneline
Note: (undo reset!) Even though the commits are no longer showing up
in the log, it is not removed from git. → If you know the commit hash you can
reset to it.
124. Last tips
• search & use help & read documentation
• don’t panic
• everything messed up: re-clone!
• test new commands in a toy repository
• don't commit large files
• don't re-write public history
• pull before push, even better, pull before starting coding
135. ü username@domain.com
ü user.name@domain.com
ü user-name@domain.com
ü username@domain.co.in
ü user_name@domain.com
× username.@domain.com
× .user.name@domain.com
× user-name@domain.com.
× username@.com
136.
137.
138. OOP Review
Slides and Presentation by Farzin Haj Gholamrezaei
Instructor: Dr.Vahidi Asl
Advanced Programming Workshop
1402 Spring semester
139. OOP Review
Why Object Oriented Programming?
Faster and easier to execute
Clear structure for programming
Easier to maintain, modify and debug
Reusability with less code and shorter development time
155. Table of contents
● The Importance of testing softwares
● Unit Test
● JUnit in Java
● Best practices in writing tests
● Advance JUnit
● Additional topics
○ GitHub workflows
○ Code coverage
2
156. Naive Approach
● Print the program’s state to standard output!
● Check the output of each method one by one manually.
● Before releasing software, add Main class to test each function and then
remove it! (Not reusing tests)
3
157. The problem with this way
● Low speed developing.
● Not cover all lines of code.
● Not reusing tests.
● The programmer must run tests manually.
● The programmer himself must ensure the test passes or not.
4
158. Benefits of Auto Testing
Let a program tests the program!
● High speed developing
● More accurate
● Debug easier after finding bugs
● Reuse tests
● Reports how many tests pass and fails
5
159. What is Unit Test?
● An automated test code
● Written and maintained by the developer
● Tests a function or an small section
● The result of every test is pass or fail
6
163. Unit Test in Java
JUnit framework
Not officially packed with JVM. Should be installed as a
dependency.
JUnit4 last release was v4.13.2 on Feb 2021
JUnit5 is the last major update.
10
165. Class Calculator
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}
12
166. import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
13
1. Create CalculatorTest class
167. import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
14
1. Create CalculatorTest class
2. Add a new method to test add
method
168. import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
15
1. Create CalculatorTest class
2. Add a new method to test add
method
3. Invoke add method in the test
method assert the result
169. import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
16
1. Create CalculatorTest class
2. Add a new method to test add
method
3. Invoke add method in the test
method assert the result
4. Add Test annotation to the test
method
170. import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
17
1. Create CalculatorTest class
2. Add a new method to test add
method
3. Invoke add method in the test
method assert the result
4. Add Test annotation to the test
method
Junit will only run methods with
Test annotation.
How JUnit knows which method has
Test annotation? Reflection
171. class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}
18
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
173. Good Test
The properties of a good test:
1. Use meaningful names for test methods.
2. Each test method should test only one thing (Single Responsibility)
3. Tests should be independent of another test.
4. Use meaningful messages for fail reason.
20
176. Startup &
Teardown Method
23
Before and after each test, these
methods will be executed.
public class BeforeAndAfterAnnotationsUnitTest {
private List<String> list;
@BeforeEach
public void init() {
System.out.println("startup");
list = new ArrayList<>(Arrays.asList("test1", "test2"));
}
@AfterEach
public void teardown() {
System.out.println("teardown");
list.clear();
}
}
177. Startup &
Teardown Method
24
Executes only once. Before any tests
and after all tests.
class BeforeAllAndAfterAllAnnotationsUnitTest {
@BeforeAll
static void setup() {
System.out.println("startup - creating DB connection");
}
@AfterAll
static void tearDown() {
System.out.println("closing DB connection");
}
}
179. Other Annotations
26
@DisplayName Declares a custom display name for the
test class or test method.
@Disabled Used to disable a test class or test
method
@Timeout lifecycle method if its execution exceeds
a given duration.
181. Test in GitHub
A GitHub workflow is a configurable, automated process that executes one or
more actions after each event (e.g. after pushing, after merging, …)
GitHub can run our repository tests on its virtual machines!
Shows passing or failing result to users.
28
182. Code Coverage
measures how many of your lines of code are
executed when you run automated tests.
Many tools are exists. One of them is Codecov
29
189. 3. Create View.
StudentView.java :
4. Use the StudentController methods to
demonstrate MVC design pattern usage.
MVCPatternDemo.java :
Output :
190.
191.
192.
193.
194.
195. Abstraction, interfaces & classes
Advanced programming
Dr. Mojtaba Vahidi Asl
Seyed Sadra Mousavi
Spring 1403
196. What is abstraction?
• Hiding implementation and showing only functionality to the user.
• Example: Sending SMS.
• You don’t know how SMS goes to the destination. You just know it goes
where you want.
• Another example: Driving a car.
• You just push a pedal and it accelerates. You don’t know the details of this
process.
• Another example: Turning on the lights.
• You don’t know the details of getting electricity to your home. You just
know that if you push the button, the light will turn on.
197. Abstraction in java
• Abstraction can be achieved by abstract classes and interfaces.
Abstract class Interface
198. Abstract classes
• They must be declared with an “abstract” keyword.
• They can’t be instantiated. (we can’t make objects from them.)
• They can have abstract and non-abstract methods.
• They can have constructors and static methods.
• They can have final methods that will force the subclass not to
change the body of the method.
200. Why we use abstract class?
• It can be used as a template class for subclasses.
• It can hold some common methods and their functionality so
we don’t have to implement them every time.
201. Interfaces
• They must be declared with an “interface” keyword.
• They are not class. So we can’t make objects of them.
• Their fields modified as final. So we can’t change them with a
setter or anything else.
• All methods are abstract by default (unless you determine
something else), So it isn’t necessary to write “abstract”
keyword.
• From Java 8, default and static methods were added to them.
• From Java 9, private methods were added to them.
• We use them for multiple inheritance.
206. Why we use interface?
• Interface help us in multiple inheritance which is a very big
favor.
• It holds the signatures of the methods which we need to be
implemented.
• It gives us loose coupling.
• This means with interfaces, we make classes independent
from each other.
• Polymorphism is supported through interface.
207. Difference between abstract class and
interface
• Abstract class is a class that can’t be instantiated and it can
have abstract and non-abstract methods.
• On the other hand, interface is something that makes the
target class to implement a set of methods.
• In abstract class we can implement some methods but we can’t
do such thing in interface.
• A class can inherit just one abstract class. But it can implement
multiple interfaces.
208. Interesting example for abstract classes and
interfaces
• You can use a general abstract class for walking and extend it for every hero instead
of writing a walking method 114 times.
• Also you can use an interface for every type of hero and put a set of methods there
so that every hero from that type implements those methods.
209. Inner classes (nested classes)
• As it occurs from its name, these classes are in other classes.
• There are 3 types of these classes:
• 1) classes which are defined in other class.
• 2) classes which are statically defined in other class.
• 3) classes which are defined in a method from other class. (They
aren’t popular.)
• They all have some weird syntax.
213. Object class
• every class in java extends object class by default.
• This class has some useful methods for itself.
• Methods like: equals, getHashCode, toString, etc.
• Equals and toString are the most useful methods of this class.
• Equals returns result of comparing hash codes of two
object.(You can override it to something else.)
• toString returns this: class name + @ + hash code of the
argument object.(You can override it to something else.)
214. Polymorphism
• It is one of the most important features of object-oriented
programming.
• It means doing an action in multiple ways.
• there are 2 types of polymorphism.
• 1) compile-time polymorphism which happens when you
overload a static method in Java.
• 2) run-time polymorphism which happens when you override
a method.
217. Binding
• Determining type of a variable or connecting a method call to
the right body method is called binding.
• There are two types of binding.
• 1) static binding: when the type is determined at compiled
time. If there is any private, static, final methods in class, there
is static binding.
• 2) dynamic binding: when the type is determined at run time.
220. Cloning
• It means creating an exact copy of an object.
• We have 2 ways to do such a thing.
• 1) using the assignment operator to create a copy of that object. (It isn’t safe.)
• 2) using clone() method to copy. This method is in cloneable interface and we
should implement it first.
• There are 2 types of cloning.
• 1) Shallow copy which is not completely safe.
• 2) Deep copy which is completely safe.
• For more information check out https://www.geeksforgeeks.org/clone-method-in-
java-2/.
235. Functional interfaces
Functional interfaces is an interface with
exactly one abstract method
Java 8 and later support non-abstract methods
in an interface called default methods.
Runnable and Comparator are some functional
interfaces.
A lambda can be used as a functional interface
238. Consumer
Use .accept(…) to do the function
BiConsumer can be useful in maps and pairs
Since its void better to be used when
outputting something to screen.
239. Function
Functional
interface
Parameters Return type
Function One parameter Generic
BiFunction Two parameter Generic
DoubleFunction
One double
parameter
Generic
UnaryOperator One parameter
Same as
parameter
BinaryOperator
Two parameters
of same type
Same as
parameter
240. Function
Use .apply(…) to do the function
Use .andThen(…) to concat them
BiFunction can be useful in maps and pairs
Because it returns an object we can use ::
(method refrence) and various functions.
246. Streams
We can use .stream() on all collections
Has one terminal operation
Use .foreach() to process each element
Can have a few intermediate operation
.filter(), .sorted(), .skip(), .limit(), .map(),
.parallel(), .reduce(), .count(), .collect(), …
249. Generics
Imagine a list implementation in Java
Does the type of content matter in the
implementation?
Why can’t we implement a list for each type?
Why can’t we just use Object class?
251. Generics
This is how they did it.
Can be useful when we don’t know or care
about the type.
Can use more than one generic
Generics can extend something to be more
limited
252. Generics
How to use?
This future is called type inference and was
introduced in java 7
The <> is called the diamond operator
253. Generics
A method can be generic too.
A generic method does not need to be inside a
generic class
Controlling generic stuff is only at compile
time
There is no difference in byte code
All types compile into their raw type
This java behavior is called erasure
259. What IS THE PROBLEM HERE??
For Special, Unusual, And Uncommon Cases, It
Does Not Work Properly!!!!
260. • The parameter "day" may be an incorrect value, such
as “Hi" which is not a date.
• The parameter "day" may not be in the desired
format, like "29 Nov 2010."
• The parameter "day" may be an empty string ("").
• The parameter "day" may be null.
We call these special cases exceptions.
261. Handling exceptions
What should we do with an exception?
• For example, if the parameter of a method is not as we expect:
u Should we terminate the program?
• Imagine a wrong input causing the whole program to crash!
• Should the method continue its execution and return a specific value (e.g., -1)?
• Maybe it shouldn't return any value (void).
• Can we determine a specific value as output?
• Should we display the error as output?
ANSWER : NONE!!!!!!!
262. What is an Exception
AN EXCEPTION IS AN UNUSUAL EVENT THAT OCCURS DURING THE EXECUTION OF A PROGRAM. IT
DISRUPTS THE NORMAL FLOW OF THE PROGRAM.
EXAMPLES:
• INVALID INPUT
• DIVISION BY ZERO
• ACCESSING AN INDEX OUTSIDE THE BOUNDS OF AN ARRAY
• HARD DISK FAILURES
• OPENING A FILE THAT DOES NOT EXIST
263. Default Behavior of Java When an Exception
Occurs:
By default, if an error or exception occurs during runtime:
• The exception is detected by the Java Virtual Machine (JVM).
• Some information about this exception is printed in the output.
• The program execution is terminated abruptly.
• However, this default behavior is usually not suitable.
265. When an exception occurs, what happens?
1- An "exception object" is created.
2- The exception object is handed over to the Java Virtual Machine (JVM).
This action is called "throwing an exception."
The exception object contains information such as:
• Error message
• Details about the type of error
• Line number in the program where the exception occurred
3- The normal execution flow of the program is halted.
266. And also:
4- The JVM looks for a responsible entity to handle the exception (the "catch" block).
• This responsible entity is called an exception handler.
• The method call stack is traversed in order to find this block.
• If such a block (exception handler) is found:
• The thrown exception object is caught by this block.
• Program execution continues from this block (normal execution is interrupted).
• The information available in the exception object is used for better management of this
specific situation.
• If such a block is not found:
• The "default Java behavior" in dealing with exceptions is executed.
• (An error message is printed in the standard output, and the program execution
terminates.)
271. Java keywords in the exception handling
• THROW
THROWS AN EXCEPTION.
• THROWS
IF A METHOD MAY THROW AN EXCEPTION, IT MUST DECLARE IT.
• TRY
BEGINS A BLOCK FOR EXCEPTION HANDLING.
• CATCH
RECEIVES AND HANDLES AN EXCEPTION.
275. Concept of Stack Trace
WHEN CATCHING AN EXCEPTION, THE FOLLOWING INFORMATION IS AVAILABLE IN THE
EXCEPTION OBJECT:
• THE ORIGINAL LOCATION WHERE THE EXCEPTION WAS THROWN.
• THE STACK OF METHODS THAT THE EXCEPTION HAS PASSED THROUGH.
A STACK TRACE IS A REPORT OF THE ACTIVE STACK FRAMES AT A PARTICULAR POINT IN
TIME DURING THE EXECUTION OF A PROGRAM. IT CONTAINS INFORMATION ABOUT THE
SEQUENCE OF METHOD CALLS THAT LED TO AN EXCEPTION OR ERROR, TYPICALLY
INCLUDING:
1.THE CLASS AND METHOD NAMES.
2.THE FILE NAME AND LINE NUMBER IN THE SOURCE CODE WHERE EACH METHOD WAS
CALLED.
3.ADDITIONAL CONTEXTUAL INFORMATION SUCH AS VARIABLE VALUES OR STATE OF THE
PROGRAM.
277. Exception Classes
• EVERY EXCEPTION HAS A TYPE.
• FOR INSTANCE, THE TYPE OF "ERROR WHEN READING A FILE" AND
"DIVISION BY ZERO ERROR" ARE DIFFERENT.
• EACH EXCEPTION IS AN OBJECT (EXCEPTION OBJECT).
• EACH OBJECT HAS A TYPE (TYPE OR CLASS).
• THE TYPE OF EXCEPTIONS HELPS IN BETTER MANAGEMENT.
• JAVA HAS DIFFERENT CLASSES FOR THIS PURPOSE. SUCH AS
NULLPOINTEREXCEPTION OR CLASSCASTEXCEPTION.
• WE CAN ALSO CREATE NEW EXCEPTION CLASSES.
280. How to Create a New Exception Class
• THE NEW CLASS MUST BE A SUBCLASS OF EXCEPTION.
• There is a class named java.lang.Exception in Java.
• Subclasses of Exception can be thrown or caught.
• EXCEPTION CLASSES ARE USUALLY SIMPLE CLASSES.
• They have few and concise methods and attributes.
• However, like all classes, they can have various constructors, attributes, and methods.
• Typically, they have a parameterless constructor and a constructor with a string
parameter that specifies the error message.
283. finally
• The part that comes in finally is executed at the end of the try-
catch execution, no matter what.
• Whether an error is thrown or not, the execution of the finally
section is guaranteed at the end of the process.
284. In any situation
• Normal completion of the execution within the try block without throwing an
error.
• Forced exit from the try block (e.g., with return, break, or continue).
• An error is thrown within the try block and caught in the catch block.
• An error is thrown within the try block and not caught in any of the catch
blocks.
• ...
The finally block is suitable for releasing acquired resources in the try block. For
example, closing a file or terminating a connection to a database. However, every
resource except memory is automatically released by garbage collection.
288. Exception Classes and Hierarchies
IN A TRY-CATCH STATEMENT:
• IF WE CATCH A SPECIFIC TYPE OF EXCEPTION IN ONE CATCH BLOCK, WE
CANNOT CATCH ITS SUBCLASS IN A SUBSEQUENT CATCH BLOCK.
• IN THIS CASE, THE COMPILER REPORTS AN ERROR: UNREACHABLE CATCH
BLOCK.
289. Exception Inheritance
Suppose a method f() is overridden in a subclass.
u f() in the subclass cannot throw more exceptions than f() in the superclass.
u The types of exceptions thrown in a method in a subclass must be a subset
of or equal to the exceptions declared in the method in the superclass.
(This refers to the exceptions specified with the throws clause.)
u Otherwise, the compiler encounters errors.
290. Why can't a method in a subclass
throw more exceptions?
• IF THIS RULE DIDN'T EXIST, DEFINING THE CLASS CHILD WITHOUT ERROR WOULD
BE IMPOSSIBLE:
• IN THIS DEFINITION, THE IS-A RELATIONSHIP BETWEEN CHILD AND PARENT WOULD BE
VIOLATED IN SOME WAY.
• FOR EXAMPLE, THE COMPILER CANNOT FORCE THE METHOD "EXAMPLE" TO
CATCH OR THROW IOEXCEPTION.
297. Table of Contents
● What is Reflection
● Examples
● Class Object
○ Method Object
○ Annotation Object
○ Field Object
● Examples of Reflection
● Dynamic Binding
● Dynamic Loading
● Generic
2
298. What is Reflection?
Sometimes the program need to know properties of itself at runtime.
● Number of class A methods
● The annotations of an specific method
● Invoke methods by knowing its name
● …
3
300. Example: RPC
Bad smell code!
5
MyRPCServer rpcServer = new MyRPCServer();
if (input == "login")
rpcServer.login();
else if (input == "logout")
rpcServer.logout();
else if (input == "function1")
rpcServer.function1();
else if (input == "function2")
rpcServer.function2();
else if (input == "function3")
rpcServer.function3();
...
301. Example: Junit
Remember?
How JUnit knows which method
is a test method?
6
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
303. Class Object
Each class has only and only one object.
Properties:
● Class name
● What are the class methods
● Annotations of methods
● Which method is private and which is public
8
304. Get Class Object
String s1 = "ABC";
String s2 = "Java";
Person p1 = new Person("Ali Alavai");
Person p2 = new Person("Taghi Taghavi");
9
ABC
Java
Ali Alavai
Taghi Taghavi
String class object
Person class object
305. Get Class Object
10
How to get the class object?
1. <class name>.class
Class c1 = Person.class;
2. Pass the full name of class to forename method:
Class c2 = Class.forName("ir.javacup.Person");
3. Invoke getClass method on the class’s objects
Object o = new Person();
Class c3 = o.getClass();
c1 == c2?
c2 == c3?
306. Get Method
Call getMethod() on the class object.
Get a method object by specifying its name and parameters.
Then call that method with invoke() method.
11
307. Get Method
class Authenticate {
public void login(String username, String password){}
...
}
Authenticate authenticate = new Authenticate();
Class classObject = Authenticate.getClass();
Method login1 = classObject.getMethod("login", String.class, String.class);
login1.invoke(authenticate, "ali1383", "abc@1234");
12
Why getMethod() also gets parameters?
308. Get Method
class Authenticate {
public void login(String username, String password){}
public void login(String username, String email, String password){}
...
}
Authenticate authenticate = new Authenticate();
Class classObject = Authenticate.getClass();
Method login1 = classObject.getMethod("login", String.class, String.class);
Method login2 = classObject.getMethod("login", String.class, String.class, String.class);
13
311. Now we have a clean code solution for
the RPC implementation problem :)
16
312. Pass methods as parameter
In high level languages (e.g. Python) we can pass functions as parameter to
another function.
Also possible in C++ with pointers.
There is not a direct way to do this in Java. But Reflection… :)
Pass method object as parameter to another method!
17
313. Get Constructor
Get a constructor by calling getConstructor() method on the class object.
Like getMethod(), gets parameters.
Then calling newInstance() on the constructor object will create a new
object.
18
314. Get Constructor
Person() {
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
Person(String name) {
this.name = name;
}
19
Class personClass = Person.class;
Constructor cons = personClass.getConstructor(String.class);
Object o = cons.newInstance("Ali");
Person c = (Person) o;
Why newInstance return an Object class
object?
We will talk about it in generic section.
315. Get Annotations
Invoke getAnnotations() method:
● On class object to get an array of all class annotations.
● On method object to get an array of all method annotations.
getAnnotations() returns An array of Annotation objects
20
316. Get Annotations
@WebService
class Authenticate{
@HTTP500
@WebMethod
public void handle500(){}
21
Annotation[] annotations = Authenticate.class.getAnnotations();
for (Annotation annotation : annotations)
System.out.println(annotation.annotationType());
annotations= Authenticate.class.getMethod("handle500").getAnnotations();
for (Annotation a : annotations)
System.out.println(a.annotationType().getSimpleName());
317. Get Field
Invoke getFields() method. On class object to get an array of all class fields.
getFields() returns An array of Fields objects.
Change the value by calling set() method on a field object.
22
318. Get Field
class Person {
String name;
int age;
}
23
Person person = new Person();
Field[] fields = Person.class.getFields();
for(Field field:fields)
if(field.getName().equals("age")) {
Object value = field.get(circle);
field.set(person, 20);
}
320. Dynamic Loading
When the class objects created?
● All of the class objects are not created and stored in memory
● If the program access the class, it will load in memory.
In other words, when the first instance is created, the class object created.
We call this Dynamic Loading in Java
25
322. Generic & Reflection
public final class Constructor<T> extends Executable
public final class Class<T> implements Serializable,...
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, ...
27
Class personClass = Person.class;
Constructor cons = personClass.getConstructor(String.class);
Object new_person = cons.newInstance("Ali");
Person new_person = (Object) o;
Class<Person> personClass = Person.class;
Constructor<Person> cons =
personClass.getConstructor(String.class);
Person new_person = cons.newInstance("Ali");
323. Generic & Reflection
28
Calling .class on generic types is not
possible.
Why?
Because Type parameters will be removed at
runtime.
class GenericType<T> {
private T element;
public void f() {
Class c2 = element.getClass();
Class c1 = T.class;
}
}
325. Constructors
1) Thread(Runnable target)
Exp. Thread t = new Thread(runnable);
2) Thread(Runnable target, String name)
Exp. Thread t = new Thread(runnable, firstThread);
3) Thread(ThreadGroup group, Runnable target)
Exp. Thread t = new Thread(g1, runnable);
4) Thread(ThreadGroup group, Runnable target, String name)
Exp. Thread t = new Thread(g1, runnable, t1);
2
326. Methods
1) start(): With this method, thread starts its work.
Exp. exampleThread.start();
2) run(): Thread will do the body of this method.
3) getState(): This method returns the state of this thread.
Exp. exampleThread.getState();
4)isAlive(): This method returns true if this thread is alive.
Exp. exampleThread.isAlive();
3
327. Methods
5) getName(): It returns the name of the thread.
Exp. exampleThread.getName();
6) setName(String name): It changes the name of this thread to
argument String.
Exp. exapleThread.setName(“test”);
7) join(): Wait for this thread to die.
Exp. exampleThread.join();
8) interrupt(): This method interrupts this thread.
Exp. exampleThread.interrupt();
4
328. Methods
9) isInterrupted(): Checks whether this thread is interrupted or not.
Exp. exampleThread.isInterrupted();
10) getPriority(): This method returns the priority of this thread.
Exp. exampleThread.getPriority();
11) setPriority(int p): This method changes the priority of this thread to
p. p should be an integer between 1 and 10.
Exp. exampleThread.setPriority(7);
12) setDaemon(Boolean on): Set this thread as either daemon or user
thread.
Exp. exampleThread.setDaemon(true);
5
329. Methods
13) isDeamon(): Checks whether this thread is daemon or not.
Exp. exampleThread.isDeamon();
14) sleep(long miliSec): Makes this thread to sleep for miliSec.
Exp. exampleThread.sleep(1000);
15) wait(): Causes this thread to wait until another thread call notify or
notifyAll.
Exp. exampleThread.wait();
16) notify(): Wakes up a single thread that is waiting on this object’s monitor.
Exp. exampleThread.notify();
PRESENTATION TITLE 6
330. Methods
17) notifyAll(): Wakes up all threads that are waiting on this object’s
monitor.
Exp. exampleThread.notifyAll();
PRESENTATION TITLE 7
334. Recap: Client-Server Communication Paradigm
Typical network app has two
pieces: client and server
application
transport
network
data link
physical
application
transport
network
data link
physical
Client:
initiates contact with server
(“speaks first”)
typically requests service from
server
request
reply
Server:
provides requested service to client
2
335. How do clients and servers communicate?
API: application programming interface
• defines interface between application
and transport layer
• socket: Internet API
• two processes communicate by sending
data into socket, reading data out of
socket
Question: how does a process “identify”
the other process with which it wants
to communicate?
• IP address of host running other process
• “port number” - allows receiving host to
determine to which local process the
message should be delivered
… more on this later.
3
336. Recap: IP & Ports
• In computer networking, a port or port number is a number assigned
to uniquely identify a connection endpoint and to direct data to a
specific service. At the software level, within an operating system, a
port is a logical construct that identifies a specific process or a type
of network service. A port at the software level is identified for
each transport protocol and address combination by the port number
assigned to it. The most common transport protocols that use port
numbers are the Transmission Control Protocol (TCP) and the User
Datagram Protocol (UDP); those port numbers are 16-bit unsigned
numbers. port numbers lower than 1024 identify the historically
most commonly used services and are called the well-known
port numbers.
4
337. Recap: IP & Ports
• The Internet Protocol (IP) is the network layer communications
protocol in the Internet Protocol Suite for relaying datagrams across
network boundaries.
• IP has the task of delivering packets from the source host to the
destination host solely based on the IP addresses in the
packet headers.
• An Internet Protocol address (IP address) is a numerical label such
as 192.0.2.1 that is assigned to a device connected to a computer
network that uses the Internet Protocol for communication. IP
addresses serve two main functions: network interface identification,
and location addressing.
5
340. Sockets
Socket: a door between application process and end-to-end
transport protocol (UCP or TCP)
process
kernel
buffers,
variables
socket
controlled by
application
developer
controlled by
operating
system
host or
server
process
kernel
buffers,
variables
socket
controlled by
application
developer
controlled by
operating
system
host or
server
internet
8
341. Decisions
• Before you go to write socket code, decide
• Do you want a TCP-style reliable, full duplex, connection oriented channel?
Or do you want a UDP-style, unreliable, message oriented channel?
• Will the code you are writing be the client or the server?
• Client: you assume that there is a process already running on another machines that you
need to connect to.
• Server: you will just start up and wait to be contacted
9
342. Socket Programming is Easy
• Create socket much like you open a file
• Once open, you can read from it and write to it
• Operating System hides most of the details
10
343. Socket Programming
Two socket types for two transport services:
• UDP: unreliable datagram
• TCP: reliable, byte stream-oriented
Application Example:
• client reads a line of characters (data) from its keyboard and sends
data to server
• server receives the data and converts characters to uppercase
• server sends modified data to client
• client receives modified data and displays line on its screen
11
344. Socket Programming: Basics
• The server application must be running before the client can send
anything.
• The server must have a socket through which it sends and receives
messages. The client also need a socket.
• Locally, a socket is identified by a port number.
• In order to send messages to the server, the client needs to know the
IP address and the port number of the server.
Port number is analogous to an apartment number. All doors (sockets)
lead into the building, but the client only has access to one of them,
located at the provided number.
12
345. OVERVIEW: TCP vs UDP
TCP service:
• connection-oriented: setup
required between client, server
• reliable transport between sending
and receiving process
• flow control: sender won’t
overwhelm receiver
• congestion control: throttle sender
when network overloaded
• does not provide: timing or
minimum bandwidth guarantees
UDP service:
• unreliable data transfer
between sending and receiving
process
• does not provide: connection
setup, reliability, flow control,
congestion control, timing, or
bandwidth guarantee
13
346. Socket Programming with TCP
client must contact server
• server process must first be running
• server must have created socket
(door) that welcomes clientʼs
contact
client contacts server by:
• Creating TCP socket, specifying IP
address, port number of server
process
• when client creates socket: client
TCP establishes connection to server
TCP
14
347. Socket Programming with TCP
• when contacted by client, server
TCP creates new socket for server
process to communicate with that
particular client
• allows server to talk with
multiple clients
• source port numbers used to
distinguish clients (more in
Chap 3)
TCP provides reliable, in-order
byte-stream transfer (“pipe”)
between client and server
application viewpoint:
15
348. Pseudo code TCP server
• Create socket (doorbellSocket)
• Bind socket to a specific port where clients can contact you
• Register with the kernel your willingness to listen that on socket for client to
contact you
• Loop
Listen to doorbell Socket for an incoming connection, get a connectSocket
Read and Write Data Into connectSocket to Communicate with client
Close connectSocket
• End Loop
• Close doorbellSocket
16
349. Pseudo code TCP client
• Create socket, connectSocket
• Do an active connect specifying the IP address and port number of
server
• Read and Write Data Into connectSocket to Communicate with server
• Close connectSocket
17
350. Socket Programming with UDP
UDP: no “connection” between client & server
• no handshaking before sending data
• sender explicitly attaches IP destination address and port # to each packet
• receiver extracts sender IP address and port# from received packet
UDP: transmitted data may be lost or received out-of-order
Application viewpoint:
UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server
18
351. Pseudo code UDP server
• Create socket
• Bind socket to a specific port where clients can contact you
• Loop
(Receive UDP Message from client x)+
(Send UDP Reply to client x)*
• Close Socket
19
352. Pseudo code UDP client
• Create socket
• Loop
(Send Message To Well-known port of server)+
(Receive Message From Server)
• Close Socket
20
353. Two Different Server Behaviors
• Iterative server
• At any time, only handles one client request
• Concurrent server
• Multiple client requests can be handled
simultaneously
• create a new process/thread to handle
each request
for (;;) {
accept a client request;
handle it
}
for (;;) {
accept a client request;
create a new process / thread to
handle request;
parent process / thread continues
}
21
354. Concurrent/Multithreaded TCP Servers
• What good is the doorbell socket? Can’t accept new connections until
call accept again anyway?
• Benefit comes in ability to hand off processing to another process or
thread
• Parent process creates the “door bell” or “welcome” socket on well-known
port and waits for clients to request connection
• When a client does connect, fork off a child process or pass to another thread
to handle that connection so that parent can return to waiting for
connections as soon as possible
22
355. Pseudo code concurrent TCP server
• Create socket doorbellSocket
• Bind
• Listen
• Loop
Accept the connection, connectSocket
Fork
If I am the child
Read/Write connectSocket
Close connectSocket
exit
• EndLoop
• Close doorbellSocket
23
358. TCP vs UDP
• TCP can use read/write (or recv/send) and source and destination are
implied by the connection; UDP must specify destination for each
datagram
• Sendto, recevfrom include address of other party
• TCP server and client code look quite different; UDP server and client
code vary mostly in who sends first
26
359. Java Sockets Programming
• The package java.net provides support for sockets programming (and
more).
• Typically you import everything defined in this package with:
import java.net.*;
27
360. Java Socket Programming API
• Class InetAddress
• Represents an Internet Protocol (IP) Address
• Class ServerSocket
• Connection-oriented server side socket
• Class Socket
• Regular connection-oriented socket (client)
• Class DatagramSocket
• Connectionless socket
28
361. InetAddress class
• static methods you can use to create new InetAddress objects.
• getByName(String host)
• getAllByName(String host)
• getLocalHost()
InetAddress x = InetAddress.getByName(
“cse.unr.edu”);
• Throws UnknownHostException
29
362. Sample Code: Lookup.java
• Uses InetAddress class to lookup hostnames found on
command line.
> java Lookup cse.unr.edu www.yahoo.com
cse.unr.edu:134.197.40.9
www.yahoo.com:209.131.36.158
30
363. try {
InetAddress a = InetAddress.getByName(hostname);
System.out.println(hostname + ":" +
a.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("No address found for " +
hostname);
}
31
364. Socket class
• Corresponds to active TCP sockets only!
• client sockets
• socket returned by accept();
• Passive sockets are supported by a different class:
• ServerSocket
• UDP sockets are supported by
• DatagramSocket
32
365. Java TCP Sockets
• java.net.Socket
• Implements client sockets (also called just “sockets”).
• An endpoint for communication between two machines.
• Constructor and Methods
• Socket(String host, int port): Creates a stream socket and connects it to
the specified port number on the named host.
• InputStream getInputStream()
• OutputStream getOutputStream()
• close()
33
366. Java TCP Sockets
• java.net.ServerSocket
• Implements server sockets.
• Waits for requests to come in over the network.
• Performs some operation based on the request.
• Constructor and Methods
• ServerSocket(int port)
• Socket Accept(): Listens for a connection to be made to this
socket and accepts it. This method blocks until a connection is
made.
34
367. Socket Constructors
• Constructor creates a TCP connection to a named TCP server.
• There are a number of constructors:
Socket(InetAddress server, int port);
Socket(InetAddress server, int port,
InetAddress local, int localport);
Socket(String hostname, int port);
35
369. Socket I/O
• Socket I/O is based on the Java I/O support
• in the package java.io
• InputStream and OutputStream are abstract classes
• common operations defined for all kinds of InputStreams,
OutputStreams…
37
370. InputStream Basics
// reads some number of bytes and
// puts in buffer array b
int read(byte[] b);
// reads up to len bytes
int read(byte[] b, int off, int len);
Both methods can throw IOException.
Both return –1 on EOF.
38
371. OutputStream Basics
// writes b.length bytes
void write(byte[] b);
// writes len bytes starting
// at offset off
void write(byte[] b, int off, int len);
Both methods can throw IOException.
39
372. ServerSocket Class (TCP Passive Socket)
• Constructors:
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog,
InetAddress bindAddr);
40
374. Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket doorbellSocket = new ServerSocket(6789);
while(true) {
Socket connectSocket = doorbellSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectSocket.getInputStream()));
Create
welcoming socket
at port 6789
Wait, on welcoming
socket for contact
by client
Create input
stream, attached
to socket
42
375. Example: Java server (TCP), cont
DataOutputStream outToClient =
new DataOutputStream(connectSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + 'n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Read in line
from socket
Create output
stream, attached
to socket
Write out line
to socket
End of while loop,
loop back and wait for
another client connection
43
376. Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket connectSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(connectSocket.getOutputStream());
Create
input stream
Create
client socket,
connect to server
Create
output stream
attached to socket
44
377. Example: Java client (TCP), cont.
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(connectSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
connectSocket.close();
}
}
Create
input stream
attached to socket
Send line
to server
Read line
from server
45
378. Client/server socket interaction: TCP (Java)
wait for incoming
connection request
connectSocket =
welcomeSocket.accept()
create socket,
port=x, fincoming request:
or
doorbellSocket =
ServerSocket()
create socket,
connect to hostid, port=x
connectSocket =
Socket()
close
connectSocket
read reply from
connectSocket
close
connectSocket
Server (running on hostid) Client
send request using
connectSocket
read request from
connectSocket
write reply to
connectSocket
TCP
connection setup
46
379. TCP Server vs Client
• Server waits to accept connection on well known port
• Client initiates contact with the server
• Accept call returns a new socket for this client connection, freeing
welcoming socket for other incoming connections
• Read and write only (addresses implied by the connection)
47
381. UDP Sockets
• DatagramSocket class
• DatagramPacket class needed to specify the payload
• incoming or outgoing
49
382. Java UDP Sockets
• In Package java.net
• java.net.DatagramSocket
• A socket for sending and receiving datagram packets.
• Constructor and Methods
• DatagramSocket(int port): Constructs a datagram socket and binds it to the specified
port on the local host machine.
• void receive( DatagramPacket p)
• void send( DatagramPacket p)
• void close()
50
385. Datagram Packet
• Contain the payload
• (a byte array)
• Can also be used to specify the destination address
• when not using connected mode UDP
53
388. Example: Java server (UDP)
import java.io.*;
import java.net.*;
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);
Create
datagram socket
at port 9876
Create space for
received datagram
Receive
datagram
56
389. Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
}
Get IP addr
port #, of
sender
Write out
datagram
to socket
End of while loop,
loop back and wait for
another datagram
Create datagram
to send to client
57
390. Example: Java client (UDP)
import java.io.*;
import java.net.*;
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("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Create
input stream
Create
client socket,
DatagramSocket,
but no port
Translate
hostname to IP
address using DNS
58
391. Example: Java client (UDP), cont.
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();
}
}
Create datagram
with data-to-send,
length, IP addr, port
Send datagram
to server
Read datagram
from server
59
392. Client/server socket interaction: UDP
close
clientSocket
Server (running on hostid)
read reply from
clientSocket
create socket,
clientSocket =
DatagramSocket()
Client
Create, address (hostid, port=x,
send datagram request
using clientSocket
create socket,
port=x, for
incoming request:
serverSocket =
DatagramSocket()
read request from
serverSocket
write reply to
serverSocket
specifying client
host address,
port umber
60
393. UDP Server vs Client
• Server has a well-known port number
• Client initiates contact with the server
• Less difference between server and client code than in TCP
• Both client and server bind to a UDP socket, server specifies port while client
does not
• Not accept for server and connect for client
• Client send to the well-known server port; server extracts the client’s
address from the datagram it receives
61
395. Socket Programming in the Real World
• Download some open source implementations of network
applications
• Web browsers (Firefox)
• DNS Servers and resolvers (BIND)
• Email clients/servers (sendmail, qmail, pine)
• telnet
• Can you find the socket code? The protocol processing? What
percentage of the code is it? What does the rest of the code do?
63
397. Resources
• Introduction to Computer Networks Slides By Amirhossein Sadr
• Dr. Mojtaba Vahidi Asl Slides
• Dr. Sadegh Aliakbari Slides
• Other Universites Slides
65