1. Sockets provide a connection between client and server programs that allows them to communicate over a network. A socket is bound to each end of the connection.
2. The Socket class implements client sockets and allows a client program to connect to a server, send and receive data, and close the connection. The ServerSocket class allows a server program to listen for connections on a port and accept sockets from clients.
3. When a client connects to a server, the server accepts the connection using ServerSocket and returns a Socket. The client and server can then communicate by getting input and output streams from the socket to send data over the connection according to the network protocol.
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
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
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
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.
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
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
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.
Remote Method Invocation, Distributed Programming in java, Java Distributed Programming, Network Programming in JAVA, Core Java, Introduction to RMI, Getting Started with RMI, Getting Started with Remote Method Invocation, Distributed Programming, Java, J2SE
Recently The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine. RMI provides for remote communication between programs written in the Java programming language.
MCIS 6163 Assignment 1/MCIS 6163 Assignment 1.pdf
Assignment 1 – MCIS 6163
Building a Simple Web Client and a Multithreaded Web Server
Objectives
To understand client-server communication via sockets.
To gain exposure to the basic operations of a Web server and client.
To explore basic structures of HTTP messages.
Due: April 14, 2020 11:59pm
Project Description
In this project, you will be developing a multithreaded Web server and a simple web client. The Web
server and Web client communicate using a text-based protocol called HTTP (Hypertext Transfer
Protocol).
Requirements for the Web server
The server is able to handle multiple requests concurrently. This means the implementation is
multithreaded. In the main thread, the server listens to a specified port, e.g., 8080. Upon receiving an
HTTP request, the server sets up a TCP connection to the requesting client and serves the request in a
separate thread. After sending the response back to the client, it closes the connection.
The server is assumed to work with HTTP GET messages. If the requested file exists, the server
responds with “HTTP/1.1 200 OK” together with the requested page to the client, otherwise it sends a
corresponding error message, e.g., “HTTP/1.1 404 Not Found” or “HTTP/1.1 400 Bad Request”.
If running the server program using command line, the syntax should be:
server_code_name [<port_number>]
where the optional <port_number> is the port on which the server is listening to connections from
clients. If the port number is not entered, the default port 8080 is used.
You can test your Web server implementation on your local machine using a Web browser, e.g.,
Internet Explorer, Firefox, or Chrome. You need to specify the used port number within the URL, for
example,
http://localhost:8080/index.htm
If omitting the port number portion, i.e., 8080, the browser will use the default port 80.
The server should response with a default page when users do not enter a specific page in the URL,
for example,
http://localhost:8080/
It should also work when the request includes a path to the requested file, for example,
http://localhost:8080/path/to/file/example.htm
You should display/log the request and header lines of request messages on the server for the purpose
of debugging.
Requirements for the simple Web client
The client is able to connect to the server via a socket and to request a page on the server.
Upon receipt of the response message from the server, the client extracts and displays/logs the
message status, and then retrieves the page content from the message body.
If running the client program using command line, the syntax should be:
client_code_name <server_IPaddress/name> [<port_number>] [<requested_file_name>]
where the <server_IPaddress/name> is the IP address or name of the Web server, e.g., 127.0.0.1 or
localhost for the server running on the local machine. The optional < ...
MCIS 6163 Assignment 1/MCIS 6163 Assignment 1.pdf
Assignment 1 – MCIS 6163
Building a Simple Web Client and a Multithreaded Web Server
Objectives
To understand client-server communication via sockets.
To gain exposure to the basic operations of a Web server and client.
To explore basic structures of HTTP messages.
Due: April 14, 2020 11:59pm
Project Description
In this project, you will be developing a multithreaded Web server and a simple web client. The Web
server and Web client communicate using a text-based protocol called HTTP (Hypertext Transfer
Protocol).
Requirements for the Web server
The server is able to handle multiple requests concurrently. This means the implementation is
multithreaded. In the main thread, the server listens to a specified port, e.g., 8080. Upon receiving an
HTTP request, the server sets up a TCP connection to the requesting client and serves the request in a
separate thread. After sending the response back to the client, it closes the connection.
The server is assumed to work with HTTP GET messages. If the requested file exists, the server
responds with “HTTP/1.1 200 OK” together with the requested page to the client, otherwise it sends a
corresponding error message, e.g., “HTTP/1.1 404 Not Found” or “HTTP/1.1 400 Bad Request”.
If running the server program using command line, the syntax should be:
server_code_name [<port_number>]
where the optional <port_number> is the port on which the server is listening to connections from
clients. If the port number is not entered, the default port 8080 is used.
You can test your Web server implementation on your local machine using a Web browser, e.g.,
Internet Explorer, Firefox, or Chrome. You need to specify the used port number within the URL, for
example,
http://localhost:8080/index.htm
If omitting the port number portion, i.e., 8080, the browser will use the default port 80.
The server should response with a default page when users do not enter a specific page in the URL,
for example,
http://localhost:8080/
It should also work when the request includes a path to the requested file, for example,
http://localhost:8080/path/to/file/example.htm
You should display/log the request and header lines of request messages on the server for the purpose
of debugging.
Requirements for the simple Web client
The client is able to connect to the server via a socket and to request a page on the server.
Upon receipt of the response message from the server, the client extracts and displays/logs the
message status, and then retrieves the page content from the message body.
If running the client program using command line, the syntax should be:
client_code_name <server_IPaddress/name> [<port_number>] [<requested_file_name>]
where the <server_IPaddress/name> is the IP address or name of the Web server, e.g., 127.0.0.1 or
localhost for the server running on the local machine. The optional <.
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docxhanneloremccaffery
[Type text] ECET465
Project 2Project 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.
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,
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
This is the 1988 issue of The Elphinstonian, the annual magazine of Elphinstone College, Mumbai. This is the special issue to commemorate the Century of the Elphinstone College Building in Mumbai.
What is gravitation, Newton's law of gravitation, projection of a satellite, derivations, weightlessness explained, change in value of g with altitude, time period of a satellite, binding energy, escape velocity of a satellite,
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
This is a 14 page question bank on the chapters of Electrostatics. This is based on the syllabus of most Board exams such as CBSE, ISCE and state boards.
Extremely important topic for Digital electronics, digital circuits, computer architecture and computer science.
Full video is available on Youtube: https://youtu.be/oyOaXqx06pY
This video explains the method of converting a decimal number to a binary number. Many solved examples are given here and also two exercises which you can attempt on your own and then check the answers.
I have also discussed the concept of LSB (least significant bit) and MSB (most significant bit), and also least significant digit (LSD) and most significant digit (MSD).
This topic is important for following courses: class 11 and 12 computer science of all state boards, class 11 and 12 physics, BSc Computer science, BSc IT, MCA (Masters degree in Computer Applications), BTech, BE (First Year), and many competitive examinations.
Free Lectures on YouTube for IGCSE Physics for the syllabus effective 2020-21. These lectures cover the syllabus of IGCSE and a major part of GCSE syllabus also.
1. The Hidden Meaning of Words in Science Question Papers
2. Scientific Notation or Powers of Ten Notation
3. Units and Base Quantities
4. What is Physics?
What is Cyber Law? Why is cyber security law needed? International cyber law. What is copyright? What are security, controls, privacy, piracy and ethics? Code of ethics for computer professionals. What is cyber insurance?
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
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.
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.
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.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
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.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Java networking programs - theory
1. Java – Networking Theory Page 1
Java – Networking
Theory
Socket Basics
In client-server applications, the server provides some service, such as processing database queries or sending
out web pages. The client uses the service provided by the server, either displaying database query results to
the user or displaying the web page in a browser. The communication that occurs between the client and the
server must be reliable. That is, no data can be dropped and it must arrive on the client side in the same order
in which the server sent it.
TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet
use to communicate with each other. To communicate over TCP, a client program and a server program
establish a connection to one another. Each program binds a socket to its end of the connection. To
communicate, the client and the server each reads from and writes to the socket bound to the connection.
What Is a Socket?
A socket is one end-point of a two-way communication link between two programs running on the network.
A socket is a connection between two hosts. It can perform seven basic operations:
1. Connect to a remote machine
2. Send data
3. Receive data
4. Close a connection
5. Bind to a port
6. Listen for incoming data
7. Accept connections from remote machines on the bound port
The java.net package provides two classes--Socket and ServerSocket--that implement the client
side of the connection and the server side of the connection, respectively.
The Socket Class
1. The java.net.Socket class is used for performing client-side TCP operations. Other client-
oriented classes that make TCP network connections, such as URL, and URLConnection all
ultimately end up invoking the methods of this class.
2. The methods of the Socket class set up and tear down connections and set as various socket
options.
3. Because TCP sockets are more or less reliable connections, the interface that the Socket class
provides to the programmer is streams. The actual reading and writing of data over the socket is
accomplished via stream classes.
4. Java's Socket class, which is used by both clients and servers, has methods that correspond to the
first four of the seven operations stated above. [The last three operations are needed only by
servers, which wait for clients to connect to them. They are implemented by the ServerSocket
class].
5. Constructors of the Socket class:
a) public Socket (String host, int port)
This connects a TCP socket to the given host and port.
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
2. 2 Java – Networking Theory
Example of use of Socket constructor:
try
{
Socket s = new Socket("www.google.com", 80);
// send and receive data...
}
catch (UnknownHostException e)
{
System.err.println(e);
}
catch (IOException e)
{
System.err.println(e);
}
b) public Socket(InetAddress host, int port) throws IOException
This constructor creates a TCP socket to the specified port on the specified host and tries to
connect. It differs from the previous constructor in that it uses an InetAddress object to
specify the host instead of a hostname. It throws an IOException if it can't connect, but does
not throw an UnknownHostException; if the host is unknown, you will find out when you
create the InetAddress object.
Example:
try
{
InetAddress iadd = InetAddress.getByName("www.google.com");
Socket s = new Socket(iadd, 80);
// send and receive data...
}
catch (UnknownHostException e)
{
System.err.println(e);
}
catch (IOException e)
{
System.err.println(e);
}
6. Other methods of Socket class:
a) Socket() – creates a socket that has not yet been initialized.
b) void connect(SocketAddress add) - connects the socket to the given address
c) void connect(SocketAddress add, int timeoutInMillisecs) –
connects the socket to the given address or returns if the time interval expired.
d) void setTimeout(int timeoutMillisecs) - sets the blocking time for read
requests on the socket. When the time out is reached, the InterruptedIOException is raised.
e) boolean isConnected() – returns true if the socket is connected
f) boolean isClosed() – returns true if the socket is closed.
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
3. Java - Networking Page 3
7. Java programs use client sockets in the following fashion:
a) The program creates a new socket with a Socket( ) constructor.
b) The socket attempts to connect to the remote host.
c) Once the connection is established, the local and remote hosts get input and output streams
from the socket and use those streams to send data to each other. This connection is full-
duplex; both hosts can send and receive data simultaneously. What the data means depends
on the protocol; different commands are sent to an FTP server than to an HTTP server. There
will normally be some agreed-upon hand-shaking followed by the transmission of data from
one to the other.
d) When the transmission of data is complete, one or both sides close the connection. Some
protocols, such as HTTP 1.0, require the connection to be closed after each request is
serviced. Others, such as FTP, allow multiple requests to be processed in a single connection.
The ServerSocket class:
1. The ServerSocket class contains everything you need to write servers in Java.
2. It has constructors that create new ServerSocket objects, methods that listen for connections on a
specified port, and methods that return a Socket object when a connection is made so that you
can send and receive data.
The basic life cycle of a server socket is:
1. A new ServerSocket is created on a particular port using a ServerSocket( ) constructor.
2. The ServerSocket listens for incoming connection on that port using its accept( ) method. When
the client connects to the server, accept( ) method returns a Socket object connecting the client
and the server.
3. Depending on the type of server, either the Socket's getInputStream() method,
getOutputStream( ) method, or both are called to get input and output streams that communicate
with the client.
4. The server and the client interact according to an agreed-upon protocol until it is time to close
the connection.
5. The server, the client, or both close the connection.
6. The server returns to step 2 and waits for the next connection.
If step 4 is likely to take a long or indefinite amount of time, certain servers create a new process to
handle each connection so that multiple clients can be serviced at the same time. Java programs
should spawn a thread to interact with the client so that the server can be ready to process the next
connection sooner.
Constructors of the ServerSocket class:
1. public ServerSocket(int port) throws IOException, BindException
This constructor creates a server socket on the port specified by the argument. If you don’t
pass the port number, the system selects an available port for you. A port chosen for you by
the system is sometimes called an anonymous port since you don't know its number.
2. public ServerSocket(int port, int queueLength) throws IOException,
BindException
This constructor creates a ServerSocket on the specified port with a queue length of your
choosing. The queueLength argument sets the length of the queue for incoming connection
requests — that is, howmany incoming connections can be stored at one time before the
host starts refusing connections. Some operating systems have a maximum queue length,
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
4. 4 Java – Networking Theory
typically five. For example, to create a server socket on port 5776 that would hold up to 100
incoming connection requests in the queue, you would write:
try
{
ServerSocket httpd = new ServerSocket(5776, 100);
}
catch (IOException e)
{
System.err.println(e);
}
The constructor throws a BindException if the socket cannot be created and bound to the
requested port. An IOException means that the port is already in use.
3. public ServerSocket(int port, int queueLength, InetAddress
bindAddress) throws IOException
• This constructor creates a ServerSocket on the specified port with the specified queue length.
This ServerSocket binds only to the specified local IP address.
• This constructor is useful for servers that run on systems with several IP addresses because it
allows you to choose the address to which you'll listen. That is, this ServerSocket listens only
for incoming connections on the specified address; it won't listen for connections that come
in through the host's other addresses. The other constructors bind to all local IP addresses by
default.
Other methods of the ServerSocket class:
Socket accept() –
A ServerSocket generally operates in a loop that repeatedly accepts connections. Each pass
through the loop invokes the accept() method. This method blocks (stops the flow of
execution) the current thread until the connection is made. The method returns a Socket
object through which the program can communicate with the client.
void close() –
Closes the server socket an stop processing any further requests.
Internet Addresses:
1. Internet addresses are numerical addresses that consist of 4 bytes in IPv4 (or 16 bytes in IPv6).
2. These addresses are written as a dotted quad like this: 132.163.4.102. Each of these quads can
vary from 0 to 255.
3. When your browser requests a web page from another computer on the Internet, it automatically
sends your computer’s address where the server should send the web page. This is called your
computer’s IP address.
4. It is easier for human beings to deal with host names such as www.google.com instead of the
numeric IP addresses.
5. IP address can be static or dynamic. A static IP address is a fixed address and cannot be changed.
A dynamic IP address changes every time the user connects to the Internet.
6. The java.net package supports IPv6 addresses provided the host computer’s OS supports these
addresses.
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
5. Java - Networking Page 5
7. The java.net package has the InetAddress class to convert between host names and Internet
addresses.
8. Methods of InetAddress class:
a) public static InetAddress getByName(String host) throws
UnknownHostException – this method determines the IP address of a host if the host
name is given.
b) static InetAddress [] getAllByName(String host) - constructs an array
of an Internet addresses for the given host name
c) static InetAddress getLocalHost() – constructs an InetAddress for the local
host
d) byte [] getAddress() – returns an array of bytes that contains numerical address.
e) String getHostAddress() – returns a string with decimal numbers separated by
periods, e.g., “132.163.4.102”
f) String getHostName() – returns the host name
The URL
1. URL is the abbreviation of Uniform Resource Locator.
2. It is a reference or an address to a resource on the Internet (e.g., java.sun.com)
3. The URL is the address of a web page; each web page has its own unique address.
4. A URL can be split into 5 parts.
Consider the URL http://www.somesite.com/dcn/chap1.html
The 5 parts of the URL are as follows:
(i) http:// - stands for the protocol. The most common protocol is the HyperText
Transfer Protocol. Others are FTP and HTTPS (Secure).
(ii) www – This is the sub domain. Some sites use the sub domain ftp, news, etc.
(iii) somesite.com – It is the host or domain name. www and the domain name combined
together give the IP address. Thus, www.somesite.com can be replaced by an IP
address.
(iv) dcn – It is a folder or directory and all files are stored in this directory.
(v) chap1.html - It is the file which is fetched from the server. If a filename is not
specified, the default file is index.html
5. The URL class
The URL class has the following constructors:
a) URL (String str) - Creates a URL object from the specified string
b) URL(URL baseurl, String relativeurl);
c) URL(String protocol, String host, int port, String file) – Creates a URL object from the
specified protocol, host, port number and file.
d) URL(String protocol, String host, String file) – Creates a URL from the specified
protocol, hostname and file name.
e) The URL object can be constructed like this:
URL add = new URL(http://www.dnaindia.com);
Such a URL is called an absolute URL. It contains all the information necessary to
reach the resource
We can also create a relative URL which contains just enough information to reach
the resource relative to another URL.
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
6. 6 Java – Networking Theory
Example: Consider the base URL http://www.somesite.com/pages Suppose the pages
on this site are page1.html and page2.html. We can create URL objects for these
pages relative to their common base URL like this:
URL add = new URL(“http://www.somesite.com/pages”);
URL pg1url = new URL(add, “page1.html”);
URL pg2url = new URL(add, “page2.html”);
[Ref Program 2 in Java Networking Programs notes]
The URLConnection Class
1. The abstract class URLConnection is the superclass of all classes that represent a
communications link between the application and a URL.
2. Instances of this class can be used both to read from and to write to the resource referenced by
the URL.
3. Creating a connection to a URL requires these steps:
i. The connection object is created by invoking the openConnection method on a URL.
ii. The setup parameters and general request properties are manipulated.
iii. The actual connection to the remote object is made, using the connect method.
iv. The remote object becomes available. The header fields and the contents of the remote
object can be accessed.
4. The following methods are used to access the header fields and the contents after the connection
is made to the remote object:
• getContent() - Retrieves the contents of this URL connection.
• getHeaderField() - Returns the value of the named header field.
• getInputStream() - Returns an input stream that reads from this open connection.
• getOutputStream() - Returns an output stream that writes to this connection.
5. Certain header fields are accessed frequently. These are:
• getContentEncoding - Returns the value of the content-encoding header field.
• getContentLength - Returns the value of the content-length header field.
• getContentType - Returns the value of the content-type header field.
• getDate - Returns the value of the date header field.
• getExpiration - Returns the value of the expires header field.
• getLastModifed – Returns the last modified date
Serving Multiple Clients
1. A typical server runs on a server computer and clients from all over the Internet might want to
use the server at the same time. The server must be able to accept incoming requests from more
than one client at a time. This can be done by using threaded programs in Java.
2. Evert time a program has established a new socket connection we will launch a new thread to
take care of the connection between the server and that client.
3. The main program will go back and wait for the next connection.
4. Thus, we have to create a loop on the server as follows:
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
7. Java - Networking Page 7
while(true)
{
Socket incoming = s.accept();
Runnable r = new ThreadedEchoHandler(incoming);
Thread t = new Thread(r);
t.start();
}
The ThreadedEchoHandler class implements the Runnable interface and contains the loop
with the client in its run method.
class ThreadedEchoHandler implements Runnable
{
…
public void run()
{
try
{
Inputstream inps = incoming.getInputStream();
OutputStream outs = incoming.getOutputStream();
//Process input and send response
incoming.close();
}
catch(Exception ex)
{
Handle exception
}
}
}
Since each connection starts a new thread, multiple clients can connect to the server at the
same time.
Sending E-Mail
1. A socket program can be used to send email.
2. To send an email, we have to make a socket connection to port 25 which is the SMTP
port (SMTP= Simple Mail Transfer Protocol). The SMTP describes the format for email
messages.
3. Steps are as follows:
i. Open a socket to the host system
Socket s = new Socket(“mail.yourserver.com”, 25); // 25 is for SMTP
PrintWriter out = new PrintWriter(s.getOutputStream());
[PrintWriter class is used to format representations of objects to a text-output
stream. Import the package java.io.Writer for this class.]
ii. Send the following information to the print stream:
HELO sending host
MAIL FROM: <sender e-mail address>
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
8. 8 Java – Networking Theory
RCPT TO : <recipient e-mail address>
DATA
mail message
(any number of lines)
QUIT
The SMTP specification requires that all lines must be terminated with r followed
by n.
Understanding Ports
Generally speaking, a computer has a single physical connection to the network. All data destined for a
particular computer arrives through that connection. However, the data may be intended for different
applications running on the computer. So how does the computer know to which application to forward the
data? Through the use of ports.
Data transmitted over the Internet is accompanied by addressing information that identifies the computer and
the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver
data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use
to deliver the data to the right application.
In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for that port.
A client can then rendezvous with the server at the server's port, as illustrated here:
Definition: The TCP and UDP protocols use ports to map incoming data to a particular process
running on a computer.
In datagram-based communication such as UDP, the datagram packet contains the port number of its
destination and UDP routes the packet to the appropriate application, as illustrated in this figure:
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers
ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP
and other system services. These ports are called well-known ports. Your applications should not attempt to
bind to them.
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
9. Java - Networking Page 9
IMPORTANT QUESTIONS
1. Explain the terms socket and port.
2. How can you get the IP address of a machine from its host name?
3. How can you find out the current IP address of your computer?
4. What is ServerSocket and how is it used?
5. Network server programs are often multithreaded. Explain what this means and why it is true.
6. Using the URL class, write a program to retrieve the file
http://www.timesofindia.com/index.html and return the last modified date of this page.
7. Explain the URL class.
8. Explain the URLConnection class
9. Explain the following methods of the URL class: getHost(), getPort(), getProtocol()
10. How can DatagramSocket and DatagramPacket be used to send information across two
computers in a network?
11. Write a Java program to accept a URL from the command line. If it uses the HTTP protocol then
find the length of its contents.
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani