0% found this document useful (0 votes)
10 views92 pages

WT Javasript

JavaScript is a versatile programming language distinct from Java, originally named 'LiveScript'. It is primarily used to enhance HTML pages with interactive features and is compatible with various platforms. The document covers fundamental aspects of JavaScript, including syntax, data types, variables, operators, functions, and object handling.

Uploaded by

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

WT Javasript

JavaScript is a versatile programming language distinct from Java, originally named 'LiveScript'. It is primarily used to enhance HTML pages with interactive features and is compatible with various platforms. The document covers fundamental aspects of JavaScript, including syntax, data types, variables, operators, functions, and object handling.

Uploaded by

tanyasrvv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

JavaScript

Language Fundamentals

1
About JavaScript
• JavaScript is not Java, or even related to Java
– The original name for JavaScript was “LiveScript”
– The name was changed when Java became popular
• Statements in JavaScript resemble statements in Java,
because both languages borrowed heavily from the C
language
– JavaScript should be fairly easy for Java programmers to learn
– However, JavaScript is a complete, full-featured, complex language
• JavaScript is seldom used to write complete “programs”
– Instead, small bits of JavaScript are used to add functionality to
HTML pages
– JavaScript is often used in conjunction with HTML “forms”
• JavaScript is reasonably platform-independent
2
Using JavaScript in a browser
• JavaScript code is included within <script> tags:
– <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
• Notes:
– The type attribute is to allow you to use other scripting languages
(but JavaScript is the default)
– This simple code does the same thing as just putting <h1>Hello
World!</h1> in the same place in the HTML document
– The semicolon at the end of the JavaScript statement is optional
• You need semicolons if you put two or more statements on the same
line
• It’s probably a good idea to keep using semicolons

3
Dealing with old browsers
• Some old browsers do not recognize script tags
– These browsers will ignore the script tags but will
display the included JavaScript
– To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
– The <!-- introduces an HTML comment
– To get JavaScript to ignore the HTML close comment, -->, the //
starts a JavaScript comment, which extends to the end of the line

Vipul kr. Verma RKGIT 4


Where to put JavaScript
• JavaScript can be put in the <head> or in the <body> of
an HTML document
– JavaScript functions should be defined in the <head>
• This ensures that the function is loaded before it is needed
– JavaScript in the <body> will be executed as the page loads
• JavaScript can be put in a separate .js file
– <script src="myJavaScriptFile.js"></script>
– Put this HTML wherever you would put the actual JavaScript code
– An external .js file lets you use the same JavaScript on multiple
HTML pages
– The external .js file cannot itself contain a <script> tag
• JavaScript can be put in HTML form object, such as a button
– This JavaScript will Vipul
be executed
kr. Verma when
RKGIT the form object is used 5
Primitive data types
• JavaScript has three “primitive” types: number, string,
and boolean
– Everything else is an object
• Numbers are always stored as floating-point values
– Hexadecimal numbers begin with 0x
– Some platforms treat 0123 as octal, others treat it as decimal
• Strings may be enclosed in single quotes or double quotes
– Strings can contains \n (newline), \" (double quote), etc.
• Booleans are either true or false
– 0, "0", empty strings, undefined, null, and NaN are
false , other values are true

Vipul kr. Verma RKGIT 6


Variables
• Variables are declared with a var statement:
– var pi = 3.1416, x, y, name = "Dr. Dave" ;
– Variables names must begin with a letter or underscore
– Variable names are case-sensitive
– Variables are untyped (they can hold values of any type)
– The word var is optional (but it’s good style to use it)
• Variables declared within a function are local to
that function (accessible only within that function)
• Variables declared outside a function are global
(accessible from anywhere on the page)
Vipul kr. Verma RKGIT 7
Operators, I
• Because most JavaScript syntax is borrowed from C (and is
therefore just like Java), we won’t spend much time on it
• Arithmetic operators:
+ - * / % ++ --
• Comparison operators:
< <= == != >= >
• Logical operators:
&& || ! (&& and || are short-circuit operators)
• Bitwise operators:
& | ^ ~ << >> >>>
• Assignment operators:
+= -= *= /= %= <<= >>= >>>=
&= ^= |=
Vipul kr. Verma RKGIT 8
Operators, II
• String operator:
+
• The conditional operator:
condition ? value_if_true : value_if_false
• Special equality tests:
– == and != try to convert their operands to the same
type before performing the test
– === and !== consider their operands unequal if
they are of different types
• Additional operators (to be discussed):
new typeof void delete
Vipul kr. Verma RKGIT 9
Comments
• Comments are as in C or Java:
– Between // and the end of the line
– Between /* and */
• Java’s javadoc comments, /** ... */, are treated
just the same as /* ... */ comments; they have no
special meaning in JavaScript

Vipul kr. Verma RKGIT 10


Statements, I
• Most JavaScript statements are also borrowed
from C
– Assignment: greeting = "Hello, " + name;
– Compound statement:
{ statement; ...; statement }
– If statements:
if (condition) statement;
if (condition) statement; else statement;
– Familiar loop statements:
while (condition) statement;
do statement while (condition);
for (initialization; condition; increment) statement;
Vipul kr. Verma RKGIT 11
Statements, II
• The switch statement:
switch (expression){
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
• Other familiar statements:
– break;
– continue;
– The empty statement, as in ;; or { }

Vipul kr. Verma RKGIT 12


JavaScript is not Java
• By now you should have realized that you already know a
great deal of JavaScript
– So far we have talked about things that are the same as in Java
• JavaScript has some features that resemble features in Java:
– JavaScript has Objects and primitive data types
– JavaScript has qualified names; for example,
document.write("Hello World");
– JavaScript has Events and event handlers
– Exception handling in JavaScript is almost the same as in Java
• JavaScript has some features unlike anything in Java:
– Variable names are untyped: the type of a variable depends on the
value it is currently holding
– Objects and arrays are defined in quite a different way
– JavaScript has with statements and a new kind of for statement
Vipul kr. Verma RKGIT 13
Exception handling, I
• Exception handling in JavaScript is almost the same as in
Java
• throw expression creates and throws an exception
– The expression is the value of the exception, and can be of any
type (often, it's a literal String)
• try {
statements to try
} catch (e) { // Notice: no type declaration for
e
exception-handling statements
} finally { // optional, as usual
code that is always executed
}
– With this form, there is only one catch clause
Vipul kr. Verma RKGIT 14
Exception handling, II
• try {
statements to try
} catch (e if test1) {
exception-handling for the case that test1 is true
} catch (e if test2) {
exception-handling for when test1 is false and test2 is true
} catch (e) {
exception-handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
• Typically, the test would be something like
e == "InvalidNameException"

Vipul kr. Verma RKGIT 15


Object literals
• You don’t declare the types of variables in JavaScript
• JavaScript has object literals, written with this syntax:
– { name1 : value1 , ... , nameN : valueN }
• Example (from Netscape’s documentation):
– car = {myCar: "Saturn", 7: "Mazda",
getCar: CarTypes("Honda"), special: Sales}
• The fields are myCar, getCar, 7 (this is a legal field name) ,
and special
• "Saturn" and "Mazda" are Strings
• CarTypes is a function call
• Sales is a variable you defined earlier
– Example use: document.write("I own a " +
car.myCar);
Vipul kr. Verma RKGIT 16
Three ways to create an object
• You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
• You can use new to create a “blank” object, and add
fields to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
• You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave");

Vipul kr. Verma RKGIT 17


Array literals
• You don’t declare the types of variables in JavaScript
• JavaScript has array literals, written with brackets and
commas
– Example: color = ["red", "yellow", "green", "blue"];
– Arrays are zero-based: color[0] is "red"
• If you put two commas in a row, the array has an “empty”
element in that location
– Example: color = ["red", , , "green", "blue"];
• color has 5 elements
– However, a single comma at the end is ignored
• Example: color = ["red", , , "green", "blue”,]; still has 5
elements

Vipul kr. Verma RKGIT 18


Four ways to create an array
• You can use an array literal:
var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty array:
– var colors = new Array();
– You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue";
colors[1]="green";
• You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
• You can use new Array(…) with two or more arguments
to create an array containing those values:
– var colors = new Array("red","green", "blue");
Vipul kr. Verma RKGIT 19
The length of an array
• If myArray is an array, its length is given by
myArray.length
• Array length can be changed by assignment beyond the
current length
– Example: var myArray = new Array(5); myArray[10] =
3;
• Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
– Example: myArray[50000] = 3; is perfectly OK
– But indices must be between 0 and 232-1
• As in C and Java, there are no two-dimensional arrays; but
you can have an array of arrays: myArray[5][3]

Vipul kr. Verma RKGIT 20


Arrays and objects
• Arrays are objects
• car = { myCar: "Saturn", 7: "Mazda" }
– car[7] is the same as car.7
– car.myCar is the same as car["myCar"]
• If you know the name of a property, you can use
dot notation: car.myCar
• If you don’t know the name of a property, but you
have it in a variable (or can compute it), you must
use array notation: car.["my" + "Car"]

Vipul kr. Verma RKGIT 21


Array functions
• If myArray is an array,
– myArray.sort() sorts the array alphabetically
– myArray.sort(function(a, b) { return a - b; })
sorts numerically
– myArray.reverse() reverses the array elements
– myArray.push(…) adds any number of new
elements to the end of the array, and increases the
array’s length
– myArray.pop() removes and returns the last element
of the array, and decrements the array’s length
– myArray.toString() returns a string containing the
values of the array elements, separated by commas
Vipul kr. Verma RKGIT 22
The for…in statement
• You can loop through all the properties of an object with
for (variable in object) statement;
– Example: for (var prop in course) {
document.write(prop + ": " +
course[prop]);
}
– Possible output: teacher: Dr. Dave
number: CIT597
– The properties are accessed in an undefined order
– If you add or delete properties of the object within the loop, it is
undefined whether the loop will visit those properties
– Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
– Notice that course["teacher"] is equivalent to
Vipul kr. Verma RKGIT 23
course.teacher
The with statement
• with (object) statement ; uses the object as the
default prefix for variables in the statement
• For example, the following are equivalent:
– with (document.myForm) {
result.value = compute(myInput.value) ;
}
– document.myForm.result.value =
compute(document.myForm.myInput.value);
• One of my books hints at mysterious problems
resulting from the use of with, and recommends
against ever using it

Vipul kr. Verma RKGIT 24


Functions
• Functions should be defined in the <head> of
an HTML page, to ensure that they are loaded first
• The syntax for defining a function is:
function name(arg1, …, argN) { statements }
– The function may contain return value; statements
– Any variables declared within the function are local to
it
• The syntax for calling a function is just
name(arg1, …, argN)
• Simple parameters are passed by value, objects are
passed by reference
Vipul kr. Verma RKGIT 25
Regular expressions
• A regular expression can be written in either of two ways:
– Within slashes, such as re = /ab+c/
– With a constructor, such as re = new RegExp("ab+c")
• Regular expressions are almost the same as in Perl or Java
(only a few unusual features are missing)
• string.match(regexp) searches string for an occurrence
of regexp
– It returns null if nothing is found
– If regexp has the g (global search) flag set, match returns an
array of matched substrings
– If g is not set, match returns an array whose 0th element is the
matched text, extra elements are the parenthesized subexpressions,
and the index property is the start position of the matched
substring

Vipul kr. Verma RKGIT 26


Warnings
• JavaScript is a big, complex language
– We’ve only scratched the surface
– It’s easy to get started in JavaScript, but if you need to
use it heavily, plan to invest time in learning it well
– Write and test your programs a little bit at a time
• JavaScript is not totally platform independent
– Expect different browsers to behave differently
– Write and test your programs a little bit at a time
• Browsers aren’t designed to report errors
– Don’t expect to get any helpful error messages
– Write and test your programs a little bit at a time

Vipul kr. Verma RKGIT 27


AJAX

Vipul kr. Verma


28 RKGIT
Synchronous web
communication

• synchronous: user must wait while new pages load


– the typical communication pattern used in web pages
(click, wait, refresh)
Vipul kr. Verma RKGIT 29
Web applications and Ajax
• web application: a dynamic web site that mimics
the feel of a desktop app
– presents a continuous user experience rather than
disjoint pages
– examples: Gmail, Google Maps, Google Docs and
Spreadsheets, Flickr, A9

Vipul kr. Verma RKGIT 30


Web applications and Ajax
• Ajax: Asynchronous JavaScript and XML
– not a programming language; a particular way of using
JavaScript
– downloads data from a server in the background
– allows dynamically updating a page without making the
user wait
– avoids the "click-wait-refresh" pattern
– Example: Google Suggest

Vipul kr. Verma RKGIT 31


Asynchronous web
communication

• asynchronous: user can keep interacting with page


while data loads
– communication pattern made possible by Ajax
Vipul kr. Verma RKGIT 32
XMLHttpRequest (and why we
won't use it)
• JavaScript includes an XMLHttpRequest object
that can fetch files from a web server
– supported in IE5+, Safari, Firefox, Opera, Chrome, etc.
(with minor compatibilities)
• it can do this asynchronously (in the background,
transparent to user)
• the contents of the fetched file can be put into
current web page using the DOM

Vipul kr. Verma RKGIT 33


XMLHttpRequest (and why we
won't use it)
• sounds great!...
• ... but it is clunky to use, and has various browser
incompatibilities
• Prototype provides a better wrapper for Ajax, so
we will use that instead

Vipul kr. Verma RKGIT 34


A typical Ajax request
1. user clicks, invoking an event handler
2. handler's code creates an XMLHttpRequest object
3. XMLHttpRequest object requests page from server
4. server retrieves appropriate data, sends it back
5. XMLHttpRequest fires an event when data arrives
– this is often called a callback
– you can attach a handler function to this event
6. your callback event handler processes the data and
displays it

Vipul kr. Verma RKGIT 35


A typical Ajax request

Vipul kr. Verma RKGIT 36


Prototype's Ajax model
new Ajax.Request("url",
{
option : value,
option : value,
...
option : value
• construct a Prototype Ajax.Request object to request a page
}
);from a server using Ajax JS
• constructor accepts 2 parameters:
1. the URL to 1. fetch, as a String,
2. a set of options, as an array of key : value pairs in {} braces (an
anonymous JS object) Vipul kr. Verma RKGIT 37
Prototype Ajax methods and
properties

options that can be passed to the Ajax.Request constructor

Vipul kr. Verma RKGIT 38


Prototype Ajax methods and
properties

events in the Ajax.Request object that you can handle

Vipul kr. Verma RKGIT 39


Basic Prototype Ajax template

function handleRequest(ajax) {
alert(ajax.responseText);
Vipul kr. Verma RKGIT 40
XMLHttpRequest security
restrictions

• cannot be run from a web page stored on your hard drive


• can only be run on a web page stored on a web server
• can only fetch files from the same site that the page is on
www.foo.com/a/b/c.html can only fetch from www.foo.com

Vipul kr. Verma RKGIT 41


Handling Ajax errors
new Ajax.Request("url",
{
method: "get",
onSuccess: functionName,
onFailure: ajaxFailure,
onException: ajaxFailure
}
);
...
function ajaxFailure(ajax, exception) {
alert("Error making Ajax request:" + "\n\nServer status:\n" + ajax.status + " " +
ajax.statusText +
"\n\nServer response text:\n" + ajax.responseText);
if (exception) {
throw exception;
}

} JS
• for user's (and developer's) benefit, show an error message if a
request fails

Vipul kr. Verma RKGIT 42


Debugging Ajax code

• Net tab shows each request, its parameters, response, any errors
• expand a request with + and look at Response tab to see Ajax result

Vipul kr. Verma RKGIT 43


Creating a POST request
new Ajax.Request("url",
{
method: "post", // optional
parameters: { name: value, name: value, ...,
name: value },
onSuccess: functionName,
onFailure: functionName,
onException: functionName
}
); JS

Vipul kr. Verma RKGIT 44


Creating a POST request
• Ajax.Request can also be used to post data to a web server
• method should be changed to "post" (or omitted; post is default)
• any query parameters should be passed as a parameters parameter
– written between {} braces as a set of name : value pairs (another
anonymous object)
– get request parameters can also be passed this way, if you like

Vipul kr. Verma RKGIT 45


Prototype's Ajax Updater
new Ajax.Updater(
"id",
"url",
{
method: "get"
}
• Ajax.Updater fetches a file and injects its content
); JS
into an element as innerHTML
• additional (1st) parameter specifies the id of element
to inject into
Vipul kr. Verma RKGIT 46
Course Outcomes of Advanced Java Programming AJP
(17625, C603)

C603.1 Design GUI using AWT and Swing .

C603.2 Develop program using event handling.

C603.3 Use network concepts (client/server, socket) in the program.

C603.4 Develop program using JDBC connectivity to access data from


database and execute different queries to get required result.

C603.5 Develop web based program using servlet and JSP

Visit for more Learning Resources


Vipul kr. Verma RKGIT 47
Java Socket Programming

Vipul kr. Verma RKGIT 48


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.*;

Vipul kr. Verma RKGIT 49


Classes
InetAddress

Socket

ServerSocket

DatagramSocket

DatagramPacket
Vipul kr. Verma RKGIT 50
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

Vipul kr. Verma RKGIT 51


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

Vipul kr. Verma RKGIT 52


try
try {{

InetAddress
InetAddress aa == InetAddress.getByName(hostname);
InetAddress.getByName(hostname);

System.out.println(hostname
System.out.println(hostname ++ ":"
":" ++
a.getHostAddress());
a.getHostAddress());

}} catch
catch (UnknownHostException
(UnknownHostException e)
e) {{

System.out.println("No
System.out.println("No address
address found
found for
for "" ++
hostname);
hostname);

}}

Vipul kr. Verma


RKGIT 53
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

Vipul kr. Verma RKGIT 54


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()

• 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.
Vipul kr. Verma RKGIT 55
Sockets

Client socket, welcoming socket (passive) and connection socket (active)

Vipul kr. Verma RKGIT 56


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);

Vipul kr. Verma RKGIT 57


Socket Methods
void close();
InetAddress getInetAddress();
InetAddress getLocalAddress();
InputStream getInputStream();
OutputStream getOutputStream();

• Lots more (setting/getting socket options, partial


close, etc.)
Vipul kr. Verma RKGIT 58
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…

Vipul kr. Verma RKGIT 59


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.
Vipul kr. Verma RKGIT 60
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.

Vipul kr. Verma RKGIT 61


ServerSocket Class
(TCP Passive Socket)
• Constructors:

ServerSocket(int port);

ServerSocket(int port, int backlog);

ServerSocket(int port, int backlog,


InetAddress bindAddr);

Vipul kr. Verma RKGIT 62


ServerSocket Methods
Socket accept();

void close();

InetAddress getInetAddress();

int getLocalPort();

throw IOException, SecurityException

Vipul kr. Verma RKGIT 63


Socket programming with
TCP keyboard monitor

Example client-server app:


• client reads line from standard

inFromUser
input
stream
input (inFromUser stream) ,
sends to server via socket Client
Process Input stream:
(outToServer stream) process sequence of
• server reads line from socket output stream: bytes

• sequence of bytes into process


server converts line to
out of process
uppercase, sends back to client

inFromServer
outToServer
output input
stream stream
• client reads, prints modified
line from socket
client TCP
(inFromServer stream) clientSocket
socket TCP
socket

to network from network

Vipul kr. Verma RKGIT 64


Client/server socket interaction:
TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
TCP create socket,
wait for incoming
connection requestconnection setup connect to hostid, port=x
clientSocket =
connectionSocket =
welcomeSocket.accept() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
Vipul kr. Verma RKGIT 65
TCPClient.java
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 clientSocket = new Socket("hostname", 6789);

DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());

Vipul kr. Verma RKGIT 66


TCPClient.java
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();

outToServer.writeBytes(sentence + '\n');

modifiedSentence = inFromServer.readLine();

System.out.println("FROM SERVER: " +


modifiedSentence);

clientSocket.close();
}
}
Vipul kr. Verma RKGIT 67
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;

ServerSocket welcomeSocket = new


ServerSocket(6789);

while(true) {

Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient = new BufferedReader(new

InputStreamReader(connectionSocket.getInputStream()));
Vipul kr. Verma RKGIT 68
TCPServer.java

DataOutputStream outToClient =
new
DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence);

}
}
}

Vipul kr. Verma RKGIT 69


Sample Echo Server
TCPEchoServer.java

Simple TCP Echo server.

Based on code from:


TCP/IP Sockets in Java

Vipul kr. Verma RKGIT 70


UDP Sockets
• DatagramSocket class

• DatagramPacket class needed to specify the payload


– incoming or outgoing

Vipul kr. Verma RKGIT 71


Socket Programming with
UDP
• UDP
– Connectionless and unreliable service.
– There isn’t an initial handshaking phase.
– Doesn’t have a pipe.
– transmitted data may be received out of order, or lost

• Socket Programming with UDP


– No need for a welcoming socket.
– No streams are attached to the sockets.
– the sending hosts creates “packets” by attaching the IP destination
address and port number to each batch of bytes.
– The receiving process must unravel to received packet to obtain the
packet’s information bytes.
Vipul kr. Verma RKGIT 72
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()

Vipul kr. Verma RKGIT 73


DatagramSocket Constructors
DatagramSocket();

DatagramSocket(int port);

DatagramSocket(int port, InetAddress a);

All can throw SocketException or SecurityException

Vipul kr. Verma RKGIT 74


Datagram Methods
void connect(InetAddress, int port);

void close();

void receive(DatagramPacket p);

void send(DatagramPacket p);

Lots more!
Vipul kr. Verma RKGIT 75
Datagram Packet
• Contain the payload
– (a byte array

• Can also be used to specify the destination address


– when not using connected mode UDP

Vipul kr. Verma RKGIT 76


DatagramPacket Constructors
For receiving:

DatagramPacket( byte[] buf, int len);

For sending:

DatagramPacket( byte[] buf, int len


InetAddress a, int port);
Vipul kr. Verma RKGIT 77
DatagramPacket methods
byte[] getData();
void setData(byte[] buf);

void setAddress(InetAddress a);


void setPort(int port);

InetAddress getAddress();
int getPort();

Vipul kr. Verma RKGIT 78


Example: Java client (UDP)
keyboard monitor

inFromUser
input
stream

Client
Process
Input: receives
process
packet (TCP
Output: sends received “byte
stream”)

receivePacket
packet (TCP sent sendPacket
UDP UDP
“byte stream”) packet packet

client UDP
clientSocket

socket UDP
socket

to network from network

Vipul kr. Verma RKGIT 79


Client/server socket interaction:
UDP
Server (running on hostid) Client
create socket,
create socket,
port=x, for clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
read request from using clientSocket
serverSocket

write reply to
serverSocket
read reply from
specifying client
clientSocket
host address,
port umber close
clientSocket

Vipul kr. Verma RKGIT 80


UDPClient.java
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();
Vipul kr. Verma RKGIT 81
UDPClient.java
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();
}
}
Vipul kr. Verma RKGIT 82
UDPServer.java
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);
Vipul kr. Verma RKGIT 83
String sentence = new String(receivePacket.getData());
UDPServer.java
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);

}
}
}
Vipul kr. Verma RKGIT 84
Sample UDP code
UDPEchoServer.java

Simple UDP Echo server.

Test using nc as the client (netcat):


> nc –u hostname port

Vipul kr. Verma RKGIT 85


Socket functional calls
• socket (): Create a socket
• bind(): bind a socket to a local IP address and port #

• listen(): passively waiting for connections


• connect(): initiating connection to another socket
• accept(): accept a new connection

• Write(): write data to a socket


• Read(): read data from a socket
• sendto(): send a datagram to another UDP socket
• recvfrom(): read a datagram from a UDP socket

• close(): close a socket (tear down the connection)


Vipul kr. Verma RKGIT 86
Java URL Class
• Represents a Uniform Resource Locator
– scheme (protocol)
– hostname
– port
– path
– query string

Vipul kr. Verma RKGIT 87


Parsing

• You can use a URL object as a parser:

URL u = new URL(“http://www.cs.unr.edu/”);

System.out.println(“Proto:” + u.getProtocol());

System.out.println(“File:” + u.getFile());

Vipul kr. Verma RKGIT 88


URL construction
• You can also build a URL by setting each part individually:

URL u = new URL(“http”,


www.cs.unr.edu,80,”/~mgunes/”);

System.out.println(“URL:” + u.toExternalForm());

System.out.println(“URL: “ + u);

Vipul kr. Verma RKGIT 89


Retrieving URL contents
• URL objects can retrieve the documents they refer to!
– actually this depends on the protocol part of the URL.
– HTTP is supported
– File is supported (“file://c:\foo.html”)
– You can get “Protocol Handlers” for other protocols.

• There are a number of ways to do this:

Object getContent();

InputStream openStream();

URLConnection openConnection();

Vipul kr. Verma RKGIT 90


Getting Header Information
• There are methods that return information extracted from
response headers:
String getContentType();
String getContentLength();
long getLastModified();

Vipul kr. Verma RKGIT 91


URLConnection
• Represents the connection (not the URL itself).

• More control than URL


– can write to the connection (send POST data).
– can set request headers.

• Closely tied to HTTP

Vipul kr. Verma RKGIT 92

You might also like