The presentation given at MSBTE sponsored content updating program on 'Advanced Java Programming' for Diploma Engineering teachers of Maharashtra. Venue: Guru Gobind Singh Polytechnic, Nashik
Date: 22/12/2010
Session: Java Network Programming
The presentation given at MSBTE sponsored content updating program on 'Advanced Java Programming' for Diploma Engineering teachers of Maharashtra. Venue: Guru Gobind Singh Polytechnic, Nashik
Date: 22/12/2010
Session: Java Network Programming
Java Network Programming getting started, Getting Started with java network programming, two tier architecture, java client server programming, core java, java to standard edition, core java, Introduction to network programming in java
Network programming in java - PPT with Easy Programs and examples of Java InetAddress Class and java socket programming example.
Learn more @ http://java2all.com/technology/network-programming
This is all about socket programming in java using TCP and UDP socket and an example of simple Echo Server.
Also includes concepts of the socket, Socket class and methods and use of those.
Java- Datagram Socket class & Datagram Packet classRuchi Maurya
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
________________________________________
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class
o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.
________________________________________
Java DatagramPacket class
Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets.
When we desire a communication between two applications possibly running on different machines, we need sockets. This presentation aims to provide knowledge of basic socket programming to undergraduate students. Basically, this presentation gives the importance of socket in the area of networking and Unix Programming. The presentation of Topic (Sockets) has designed according to the Network Programming Subject, B.Tech, 6th Semester syllabus of Punjab Technical University Kapurthala, Punjab.
Java Network Programming getting started, Getting Started with java network programming, two tier architecture, java client server programming, core java, java to standard edition, core java, Introduction to network programming in java
Network programming in java - PPT with Easy Programs and examples of Java InetAddress Class and java socket programming example.
Learn more @ http://java2all.com/technology/network-programming
This is all about socket programming in java using TCP and UDP socket and an example of simple Echo Server.
Also includes concepts of the socket, Socket class and methods and use of those.
Java- Datagram Socket class & Datagram Packet classRuchi Maurya
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
________________________________________
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class
o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.
________________________________________
Java DatagramPacket class
Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets.
When we desire a communication between two applications possibly running on different machines, we need sockets. This presentation aims to provide knowledge of basic socket programming to undergraduate students. Basically, this presentation gives the importance of socket in the area of networking and Unix Programming. The presentation of Topic (Sockets) has designed according to the Network Programming Subject, B.Tech, 6th Semester syllabus of Punjab Technical University Kapurthala, Punjab.
The Presentation given at Guru Gobind Singh Polytechnic, Nashik for Third Year Information Technology and Computer Engineering Students on 08/02/2011.
Topic: Java Network Programming
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxkacie8xcheco
Project Assignment 2: Building a Multi-Threaded Web Server
This project assignment is due at the end of the seventh week of the course and is worth 7% of your total grade.
In this project, we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous service requests in parallel. Section 2.7 of your text may offer you some insight and help. You should be able to demonstrate that your Web server is capable of delivering your home page to a Web browser.
We are going to implement Version 1.0 of HTTP, as defined in
RFC 1945
, where separate HTTP requests are sent for each component of the Web page. The server will be able to handle multiple simultaneous service requests in parallel. This means that the Web server is multi-threaded. In the main thread, the server listens to a fixed port. When it receives a TCP connection request, it sets up a TCP connection through another port and services the request in a separate thread. To simplify this programming task, we will develop the code in two stages. In the first stage, you will write a multi-threaded server that simply displays the contents of the HTTP request message that it receives. After this program is running properly, you will add the code required to generate an appropriate response.
As you are developing the code, you can test your server from a Web browser. Just remember that you are not serving through the standard port 80, so you need to specify the port number within the URL that you give to your browser. For example, if your machine's name is
host.someschool.edu
, your server is listening to port 6789, and you want to retrieve the file
index.html
, then you would specify the following URL within the browser:
http://host.someschool.edu:6789/index.html
If you omit ":6789," the browser will assume port 80, which most likely will not have a server listening on it.
When the server encounters an error, it sends a response message with the appropriate HTML source so that the error information is displayed in the browser window.
Web Server in Java: Part A
In the following steps, we will go through the code for the first implementation of our Web server. Wherever you see "?," you will need to supply a missing detail.
Our first implementation of the Web server will be multi-threaded, where the processing of each incoming request will take place inside a separate thread of execution. This allows the server to service multiple clients in parallel, or to perform multiple file transfers to a single client in parallel. When we create a new thread of execution, we need to pass to the Thread's constructor an instance of some class that implements the
Runnable
interface. This is the reason why we define a separate class called
HttpRequest
. The structure of the Web server is shown below:
import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class WebServer
{
public static void main(S.
Networking: Protocol, Sockets, Knowing IP Address, URL, Reading the Source Code of a Web Page, Downloading a Web Page from Internet, Downloading an Image from Internet, A TCP/IP Server, A TCP/IP Client, A UDP Server, A UDP Client, File Server, File Client, Two-Way Communication between Server and Client, Sending a Simple Mail,
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
2. Objective and Outline
• Objective:
– Introduction to Java networking features
• It is much easier to write networking programs inJava than in C++
• But less efficient.
• Outline
– Motivating example: ICQ Server and Client
– Networking basics
• IP addresses, ports, protocols, client-server interaction
– Socket-level programming
• Writing a client (Socket)
• Writing a server (ServerSocket)
• Example: writing your own icq
– Communicating with web servers
• Retrieving information (URL, URLConnection)
• Sending information
3. Networking Basics
• Internet protocol (IP) addresses
– Every host on Internet has a unique IP address
143.89.40.46, 203.184.197.198
203.184.197.196, 203.184.197.197, 127.0.0.1
– More convenient to refer to using hostname string
cs.ust.hk, tom.com, localhost
– One hostname can correspond to multiple internet addresses:
• www.yahoo.com:
66.218.70.49; 66.218.70.50; 66.218.71.80; 66.218.71.84; …
– Domain Naming Service (DNS) maps names to numbers
4. java.net.InetAddress class converts between
hostnames and internet addresses
InetAddress tm = InetAddress.getByName(“www.yahoo.com");
InetAddress tm= InetAddress.getByName(“localhost");
//127.0.0.1
InetAddress tm = InetAddress.getLocalHost();
Can get array of addresses (if more than one)
InetAddress[] addrs;
addrs=InetAddress.getAllByName(“www.yahoo.com");
for (int i = 0; i < addr.length; i++)
System.out.println(addrs[i].getHostAddress());
InetAddressTest.java
Networking Basics
5. Ports
Many different services can be running on the host
A port identifies a service within a host
Many standard port numbers are pre-assigned
time of day 13, ftp 21, telnet 23, smtp 25, http 80
see /etc/services on workstation for list of all assigned ports
IP address + port number = "phone number“ for service
Networking Basics
6. protocols : rules that facilitate communications between
machines
Examples:
HTTP: HyperText Transfer Protocol
FTP: File Transfer Protocol
SMTP: Simple Message Transfer Protocol
TCP: Transmission Control Protocol
UDP: User Datagram Protocol, good for, e.g., video delivery)
Protocols are standardized and documented
So machines can reliably work with one another
Networking Basics
7. Client-Server interaction
Communication between hosts is two-way, but usually
the two hosts take different roles
Server waits for client to make request
Server registered on a known port with the host ("public phone
number")
Usually running in endless loop
Listens for incoming client connections
Networking Basics
8. Client "calls" server to start a conversation
Client making calls uses hostname/IP address and port number
Sends request and waits for response
Standard services always running
ftp, http, smtp, etc. server running on host using expected port
Server offers shared resource (information,database, files,
printer, compute power) to clients
Networking Basics
9. Using telnet to try out some services of servers:
Telnet assumes you want to connect to port 23 on the
receiving host (port 23 is where the telnet server is listening)
However there is an optional argument after the hostname
that allows you to connect to a different port
Try the following
Get time: telnet time-A.timefreq.bldrdoc.gov 13
Get HTML page: telnet www.cs.ust.hk 80 and enter a GET command
Many servers now refuse telnet connections due to security reasons.
Networking Basics
10. Outline
• Outline
– Networking basics
• IP addresses, ports, protocols, client-server interaction
– Socket-level programming
• Writing a client
• Writing a server
• Example: writing your own icq
– Communicating with web servers
• Retrieving information
• Sending information
11. Socket-Level Programming
Socket is an abstraction of one type of bi-directional
communication channel between hosts
Send and receive data using streams
Next:
How to write a client
How to write a server
Client Server
OutputStream
InputStream
InputStream
OutputStream
12. • To write a client socket using java.net.Socket
– Create a new Socket with hostname and port number of the connection
Socket s = New Socket(String hostName,int
portNumber);
– Call s.getOutputStream() and s.getInputStream() to
get streams for sending and receiving infomation
– Need to learn protocol used to communicate
• Know how to properly form requests to send to server
• Know how to interpret the server’s responses
Writing Clients
13. Writing Clients
SocketTest:
Makes a socket connection to the atomic clock in Boulder, Colorado,
and prints the time that the server sends.
try
{ Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
BufferedReader in = new BufferedReader
(new InputStreamReader( s.getInputStream() ));
// read from in
}
catch (IOException e)
{ e.printStackTrace();
}
14. Writing Servers
To write a server using java.net.ServerSocket
Create a new ServerSocket with a port number to listen on the port
ServerSocket s = New ServerSocket( portNumber);
Use accept() to listen on the port.
accept() returns a socket incoming when a client calls
Socket incoming = s.accept();
Call incoming.getOutputStream() and
incoming.getInputStream() to get streams for sending and
receiving information
15. Writing Servers
Example: Echo server
ServerSocket s = new ServerSocket(8189);
Socket incoming = s.accept( );
BufferedReader in = new BufferedReader
(new InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter
(incoming.getOutputStream(), true /* autoFlush */ );
out.println( "Hello! Enter BYE to exit." );
…
EchoServer.java
16. A side note
• Many machines in CSD now refuse socket
connections due to security considerations.
• However, you can
– Run severs on any lab 4 machine and connect to
the server from any other lab 4 machines.
– Run severs on one of scpu1-14 and connect to the
server from others or from the PC network.
17. Multithread server: starts a separate thread for each connection.
public class ThreadedEchoServer
{ public static void main(String[] args )
{ int i = 1;
try{ServerSocket s = new ServerSocket(8190);
while (true)
{ Socket incoming = s.accept( );
System.out.println("Spawning " + i);
new ThreadedEchoHandler(incoming, i).start();
i++;
}
} catch (Exception e) …. //ThreadedEchoServer.java
Writing Servers
18. class ThreadedEchoHandler extends Thread
{ public ThreadedEchoHandler(Socket i, int c)
{ incoming = i; counter = c; }
public void run()
{ try
{ BufferedReader in = new BufferedReader
(new InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter
(incoming.getOutputStream(), true /* autoFlush */);
out.println( "Hello! Enter BYE to exit." );
…
private Socket incoming;
private int counter; }
Writing Servers
19. • A more interesting example
– ICQServer.java
• A simple server that listens on port 7777.
• Connect two clients so that they can talk to each other.
• Can handle more than one pairs.
– ICQClient.java
• Allows user to connect to ICQServer and have one-to-
one conversation with partner
Servers & Client
20. Outline
• Outline
– Networking basics
• IP addresses, ports, protocols, client-server interaction
– Socket-level programming
• Writing a client
• Writing a server
• Example: writing your own icq
– Communicating with web servers
• Retrieving information
• Sending information
21. • Reason for communicating with web servers
– To retrieve/send information
• Need to indicate location of resource
– URL stands for Uniform Resource Locator
• Neat scheme for uniquely identifying all kinds of network resources
– Basic form <protocol>:<sitename><pathname>
• http://www.cs.ust.hk/~lzhang/comp201/index.html
• ftp://ftp.cs.ust.hk/pub/lzhang/teach/201/codes/HttpTest/HttpTest.jav
a
• file:/MyDisk/Letters/ToMom2-11-98
• Protocols include files, http, ftp, gopher, news, mailto, etc.
Communicating with web servers
22. • Class java.net.URL represents a Uniform Resource Locator
– Create an java object that represents an URL
URL url = new
URL(“http://www.cs.ust.hk/~lzhang/comp201/index.html”);
• getHost(), getPath(), getPort(), getProtocol()
• java.net.URLConnection represents a communication link between the
application and a URL.
– Constructor:
• URLConnection cnn = new URLConnection( url)
– Obtainable also from URL:
• URLConnection cnn = url.openConnection();
Communicating with web servers
23. Communicating with web servers
• Steps for working with java.net.URLConnection
– Set properties of connection:
• setDoInPut(true) //default
• setDoOutPut(true) for sending information to the server
• …
– Make connection: cnn.connect();
– Query header information:
• getContentType, getContentLength,
getContentEncoding,
getDate, getExpiration, getLastModified
– getInputStream for reading and getOutputStream
for writing
• API of the class has a more detailed description.
24. Communicating with web servers
• Can directly open a stream for reading in URL class:
– public final InputStream openStream() throws IOException
url.opentStream()
• Opens a connection to this URL and returns an InputStream for
reading from that connection.
• This method is a shorthand for:
openConnection().getInputStream()
URLTest.java
25. Retrieving Information
• URLConnectionTest.java
URL url = new URL(urlName);
URLConnection connection = url.openConnection();
connection.connect();
// print header fields
int n = 1;
String key;
while ((key = connection.getHeaderFieldKey(n)) != null)
{
String value = connection.getHeaderField(n);
System.out.println(key + ": " + value);
n++;
}
27. Retrieving Information
// print first ten lines of contents
BufferedReader in = new BufferedReader(new
InputStreamReader( connection.getInputStream() ));
String line;
n = 1;
while ((line = in.readLine()) != null && n <= 10)
{
System.out.println(line);
n++;
}
if (line != null) System.out.println(". . .");
28. Sending Information
Web servers receive information from clients using either GET or
POST
GET requests are requests made by browsers when the user
types in a URL on the address line,
follows a link from a Web page, or
makes an HTML form that does not specify a METHOD or specifically use
the GET method.
POST requests are generated when someone creates an HTML
form that specifies METHOD="POST"
Examples:
http://maps.yahoo.com/py/maps.py: python,
<form action="/py/maps.py?Pyt=Tmap&YY=28457" method=GET> … </form>
http://www.census.gov/ipc/www/idbprint.html:
<form method=post action="/cgi-bin/ipc/idbsprd">
29. Sending Information
Appropriate CGI (common gateway interface) script is called to
process info received and produce an HTML page to send back to
client
CGI scripts usually written in C, Perl, shell script. (Out of the scope
of this course.)
Will discuss servlets, Java alternative to CGI scripts
30. • Our task: Write java program to communicate
with CGI scripts
– The way we send parameters to a CGI script
depends on
• The parameters that CGI scripts expects
– What to send
• The way a CGI script receives parameters
– How to send
Sending Information
31. Send information to CGI script using GET
Attach parameters to the end of URL
http://host/script?parameters
Separate parameters using “&” and encode parameters as
follows to avoid misinterpretation (URL encoding)
Replace space with “+”
Replace each non-alphanumeric character with “%” followed by the
hexadecimal code of the character
“Mastering C++” “Mastering+C%2b%2b”
Disadvantage: long parameter string, might exceed limits of browsers.
GetTest.java
Sending Information
32. Sending information to CGI script using POST:
Open URLConnection and send parameter using a stream
Open a URLConnection:
URL url = new URL(“http:/host/script”);
URLConnection cnn = url.openConnection();
Set up connection for output:
cnn.setDoOutput(true);
Sending Information
33. Get a stream for sending data:
PrinterWriter out = new
PrintWriter(cnn.getOutputStream());
Send parameters
Out.print(name1 + “=“ + URLEncoder.encode(value1, “UTF-8”) + “&” );
Out.print(name2 + “=“ + URLEncoder.encode(value2, “UTF-8”) ) + “n”);
Note: URLEncoder: Utility class for HTML form encoding.
This class contains static methods for converting a String to the application/x-www-
form-urlencoded MIME (Multipurpose Internet Mail Extensions ) format.
The World Wide Web Consortium Recommendation states that the UTF-8 encoding
scheme should be used.
PostTest.java
Sending Information