This document discusses network programming clients. It begins by defining clients and servers, explaining that clients initiate connections by specifying a host and port, while servers listen on a port without specifying a host. It then provides the basic steps for implementing a generic network client in Java: creating a socket, input and output streams, performing I/O, and closing the socket. Additional topics covered include parsing strings with StringTokenizer, an example client that verifies email addresses, and a MailAddress class to parse email addresses.
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
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 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
Short overview of the XML-RPC protocol for XML-based RPC services.
XML-RPC is a remote procedure call protocol using XML as data format and HTTP as transport protocol.
It is a simple mechanism to call remote procedures on a machine with a different operating system.
XML-RPC is language and platform independent. XML-RPC libraries are available in Java and other languages.
XML-RPC is not more than its name implies and thus is very simple and lean. This means that it lacks most of the features that SOAP/WSDL web services provide.
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 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
Short overview of the XML-RPC protocol for XML-based RPC services.
XML-RPC is a remote procedure call protocol using XML as data format and HTTP as transport protocol.
It is a simple mechanism to call remote procedures on a machine with a different operating system.
XML-RPC is language and platform independent. XML-RPC libraries are available in Java and other languages.
XML-RPC is not more than its name implies and thus is very simple and lean. This means that it lacks most of the features that SOAP/WSDL web services provide.
Created for Palm Springs Public Library's teen program - "The 2nd Annual Zombie Awareness Month Event." Includes links to videos (YouTube) to supplement slides. Covers history of zombies, zombies myths in other cultures, and how to prepare for a zombie outbreak.
[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.
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
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 Raspberry Pi is a series of credit card–sized single-board computers developed in the UK by the Raspberry Pi Foundation with the intention of promoting the teaching of basic computer science in schools.
The original Raspberry Pi and Raspberry Pi 2 are manufactured in several board configurations through licensed manufacturing agreements with Newark element14 (Premier Farnell), RS Components and Egoman. These companies sell the Raspberry Pi online. Egoman produces a version for distribution solely in China and Taiwan, which can be distinguished from other Pis by their red colouring and lack of FCC/CE marks. The hardware is the same across all manufacturers.
The original Raspberry Pi is based on the Broadcom BCM2835 system on a chip (SoC), which includes an ARM1176JZF-S 700 MHz processor, VideoCore IV GPU, and was originally shipped with 256 megabytes of RAM, later upgraded (models B and B+) to 512 MB. The system has Secure Digital (SD) (models A and B) or MicroSD (models A+ and B+) sockets for boot media and persistent storage.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
2. Network Programming: Clients2 www.corewebprogramming.com
Agenda
• Creating sockets
• Implementing a generic network client
• Parsing data using StringTokenizer
• Retrieving files from an HTTP server
• Retrieving Web documents by using the
URL class
3. Network Programming: Clients3 www.corewebprogramming.com
Client vs. Server
• Traditional definition
– Client: User of network services
– Server: Supplier of network services
• Problem with traditional definition
– If there are 2 programs exchanging data, it seems unclear
– Some situations (e.g., X Windows) seem reversed
• Easier way to remember distinction
– Server starts first. Server doesn't specify host (just port).
– Client starts second. Client specifies host (and port).
• Analogy: Company phone line
– Installing phone is like starting server
– Extension is like port
– Person who calls is the client: he specifies both host
(general company number) and port (extension)
4. Network Programming: Clients4 www.corewebprogramming.com
Client vs. Server (Continued)
• If server has to start first, why are we
covering clients before we cover servers?
– Clients are slightly easier.
– We can test clients by connecting to existing servers that
are already on the internet.
• Point: clients created in Java need not
communicate with servers written in Java.
– They can communicate with any server that accepts
socket connections (as long as they know the proper
communication protocol).
– Exception: ObjectInputStream and ObjectOutputStream
allow Java programs to send complicated data structures
back and forth. Only works in Java, though.
5. Network Programming: Clients5 www.corewebprogramming.com
Steps for Implementing a Client
1. Create a Socket object
Socket client = new Socket("hostname", portNumber);
2. Create an output stream that can be used to send
info to the Socket
// Last arg of true means autoflush -- flush stream
// when println is called
PrintWriter out =
new PrintWriter(client.getOutputStream(), true);
3. Create an input stream to read the response from
the server
BufferedReader in =
new BufferedReader
(new InputStreamReader(client.getInputStream()));
6. Network Programming: Clients6 www.corewebprogramming.com
Steps for Implementing a Client
(Continued)
4. Do I/O with the input and output Streams
– For the output stream, PrintWriter, use print and println, similar to
System.out.println
• The main difference is that you can create
PrintWriters for different Unicode
characters sets, and you can’t with
PrintStream (the class of System.out).
– For the input stream, BufferedReader, you can call read to get a
single character or an array of characters, or call readLine to get a
whole line
• Note that readLine returns null if the
connection was terminated (i.e. on EOF),
but waits otherwise
5. Close the socket when done
client.close();
• Also closes the associated input and
7. Network Programming: Clients7 www.corewebprogramming.com
A Generic Network Client
import java.net.*;
import java.io.*;
/** A starting point for network clients. */
public class NetworkClient {
protected String host;
protected int port;
public NetworkClient(String host, int port) {
this.host = host;
this.port = port;
}
public String getHost() {
return(host);
}
public int getPort() {
return(port);
}
...
8. Network Programming: Clients8 www.corewebprogramming.com
A Generic Network Client
(Continued)
...
/** Establishes the connection, then passes the socket
* to handleConnection. */
public void connect() {
try {
Socket client = new Socket(host, port);
handleConnection(client);
} catch(UnknownHostException uhe) {
System.out.println("Unknown host: " + host);
uhe.printStackTrace();
} catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
...
9. Network Programming: Clients9 www.corewebprogramming.com
A Generic Network Client
(Continued)
/** This is the method you will override when
* making a network client for your task.
* This default version sends a single line
* ("Generic Network Client") to the server,
* reads one line of response, prints it, then exits.
*/
protected void handleConnection(Socket client)
throws IOException {
PrintWriter out =
SocketUtil.getPrintWriter(client);
BufferedReader in =
SocketUtil.getBufferedReader(client);
out.println("Generic Network Client");
System.out.println
("Generic Network Client:n" +
"Made connection to " + host +
" and got '" + in.readLine() + "' in response");
client.close();
}
}
10. Network Programming: Clients10 www.corewebprogramming.com
SocketUtil – Simplifying
Creation of Reader and Writer
import java.net.*;
import java.io.*;
public class SocketUtil {
/** Make a BufferedReader to get incoming data. */
public static BufferedReader getBufferedReader
(Socket s) throws IOException {
return(new BufferedReader(
new InputStreamReader(s.getInputStream())));
}
/** Make a PrintWriter to send outgoing data.
* This PrintWriter will automatically flush stream
* when println is called.
*/
public static PrintWriter getPrintWriter(Socket s)
throws IOException {
// 2nd argument of true means autoflush
return(new PrintWriter(s.getOutputStream(), true));
}
}
11. Network Programming: Clients11 www.corewebprogramming.com
Example Client
public class NetworkClientTest {
public static void main(String[] args) {
String host = "localhost";
if (args.length > 0)
host = args[0];
int port = 8088;
if (args.length > 1)
port = Integer.parseInt(args[1]);
NetworkClient nwClient
= new NetworkClient(host, port);
nwClient.connect();
}
}
12. Network Programming: Clients12 www.corewebprogramming.com
Example Client, Result
> java NetworkClientTest ftp.netscape.com 21
Generic Network Client:
Made connection to ftp.netscape.com and got
‘220 ftp26 FTP server (UNIX(r) System V Release 4.0)
ready.’ in response
>
13. Network Programming: Clients13 www.corewebprogramming.com
Aside: Parsing Strings Using
StringTokenizer
• Idea
– Build a tokenizer from an initial string
– Retrieve tokens one at a time with nextToken
– You can also see how many tokens are remaining
(countTokens) or simply test if the number of tokens
remaining is nonzero (hasMoreTokens)
StringTokenizer tok
= new StringTokenizer(input, delimiters);
while (tok.hasMoreTokens()) {
doSomethingWith(tok.nextToken());
}
14. Network Programming: Clients14 www.corewebprogramming.com
StringTokenizer
• Constructors
– StringTokenizer(String input, String delimiters)
– StringTokenizer(String input, String delimiters,
boolean includeDelimiters)
– StringTokenizer(String input)
• Default delimiter set is " tnrf" (whitespace)
• Methods
– nextToken(), nextToken(String delimiters)
– countTokens()
– hasMoreTokens()
• Also see methods in String class
– substring, indexOf, startsWith, endsWith, compareTo, …
– JDK 1.4 has regular expressions in java.util.regex!
15. Network Programming: Clients15 www.corewebprogramming.com
Interactive Tokenizer: Example
import java.util.StringTokenizer;
public class TokTest {
public static void main(String[] args) {
if (args.length == 2) {
String input = args[0], delimiters = args[1];
StringTokenizer tok
= new StringTokenizer(input, delimiters);
while (tok.hasMoreTokens()) {
System.out.println(tok.nextToken());
}
} else {
System.out.println
("Usage: java TokTest string delimiters");
}
}
}
16. Network Programming: Clients16 www.corewebprogramming.com
Interactive Tokenizer: Result
> java TokTest http://www.microsoft.com/~gates/ :/.
http
www
microsoft
com
~gates
> java TokTest "if (tok.hasMoreTokens()) {" "(){. "
if
tok
hasMoreTokens
17. Network Programming: Clients17 www.corewebprogramming.com
A Client to Verify Email
Addresses
• Talking to a mail server
– One of the best ways to get comfortable with a
network protocol is to telnet to the port a server is
on and try out commands interactively
• Example talking to apl.jhu.edu’s server
> telnet apl.jhu.edu 25
Trying 128.220.101.100 ...Connected … Escape character …
220 aplcenmp.apl.jhu.edu Sendmail SMI-8.6/SMI-SVR4 ready …
expn hall
250 Marty Hall <hall@aplcenmp.apl.jhu.edu>
expn root
250 Gary Gafke <…>
250 Tom Vellani <…>
quit
221 aplcenmp.apl.jhu.edu closing connection
Connection closed by foreign host.
18. Network Programming: Clients18 www.corewebprogramming.com
Address Verifier
/** Given an email address of the form user@host,
* connect to port 25 of the host and issue an
* 'expn' request for the user. Print the results.
*/
public class AddressVerifier extends NetworkClient {
private String username;
public static void main(String[] args) {
MailAddress address = new MailAddress(args[0]);
AddressVerifier verifier
= new AddressVerifier(address.getUsername(),
address.getHostname(),
25);
verifier.connect();
}
...
19. Network Programming: Clients19 www.corewebprogramming.com
Address Verifier (Continued)
protected void handleConnection(Socket client) {
try {
PrintWriter out =
SocketUtil.getPrintWriter(client);
InputStream in = client.getInputStream();
byte[] response = new byte[1000];
// Clear out mail server's welcome message.
in.read(response);
out.println("EXPN " + username);
// Read the response to the EXPN command.
// May be multiple lines!
int numBytes = in.read(response); // Can't use readLine!
// The 0 means to use normal ASCII encoding.
System.out.write(response, 0, numBytes);
out.println("QUIT");
client.close();
} catch(IOException ioe) {
System.out.println("Couldn't make connection: "
+ ioe);
}
}
...}
20. Network Programming: Clients20 www.corewebprogramming.com
MailAddress
// Takes a string of the form "user@host" and
// separates it into the "user" and "host" parts.
public class MailAddress {
private String username, hostname;
public MailAddress(String emailAddress) {
StringTokenizer tokenizer
= new StringTokenizer(emailAddress, "@");
this.username = getArg(tokenizer);
this.hostname = getArg(tokenizer);
}
private static String getArg(StringTokenizer tok) {
try { return(tok.nextToken()); }
catch (NoSuchElementException nsee) {
System.out.println("Illegal email address");
return(null);
}
}...
}
21. Network Programming: Clients21 www.corewebprogramming.com
Address Verifier: Result
> java AddressVerifier tbl@w3.org
250 <timbl@hq.lcs.mit.edu>
> java AddressVerifier timbl@hq.lcs.mit.edu
250 Tim Berners-Lee <timbl>
> java AddressVerifier gosling@mail.javasoft.com
550 gosling... User unknown
22. Network Programming: Clients22 www.corewebprogramming.com
Brief Aside: Using the HTTP
GET Command
• For the URL http://www.apl.jhu.edu/~lmb/
Unix> telnet www.apl.jhu.edu 80
Trying 128.220.101.100 ...
Connected to aplcenmp.apl.jhu.edu.
Escape character is '^]'.
GET /~lmb/ HTTP/1.0
HTTP/1.0 200 Document follows
Date: Sat, 30 Jun 2001 14:34:58 GMT
Server: NCSA/1.5.2
Last-modified: Tue, 11 Jul 2001 15:13:56 GMT
Content-type: text/html
Content-length: 50479
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
...
</HTML>Connection closed by foreign host.
Unix>
23. Network Programming: Clients23 www.corewebprogramming.com
Talking to Web Servers
Interactively
• WebClient
– Simple graphical user interface to communicate with
HTTP servers
– User can interactively specify:
• Host
• Port
• HTTP request line
• HTTP request headers
– HTTP request is performed in a separate thread
– Response document is placed in a scrollable text area
– Download all source files for WebClient from
http://archive.corewebprogramming.com/Chapter17.html
25. Network Programming: Clients25 www.corewebprogramming.com
A Class to Retrieve a Given URI
from a Given Host
import java.net.*;
import java.io.*;
public class UriRetriever extends NetworkClient {
private String uri;
public static void main(String[] args) {
UriRetriever uriClient
= new UriRetriever(args[0],
Integer.parseInt(args[1]),
args[2]);
uriClient.connect();
}
public UriRetriever(String host, int port,
String uri) {
super(host, port);
this.uri = uri;
}
...
26. Network Programming: Clients26 www.corewebprogramming.com
A Class to Retrieve a Given URI
from a Given Host (Continued)
// It is safe to use blocking IO (readLine) since
// HTTP servers close connection when done,
// resulting in a null value for readLine.
protected void handleConnection(Socket uriSocket)
throws IOException {
PrintWriter out =
SocketUtil.getPrintWriter(uriSocket);
BufferedReader in =
SocketUtil.getBufferedReader(uriSocket);
out.println("GET " + uri + " HTTP/1.0n");
String line;
while ((line = in.readLine()) != null) {
System.out.println("> " + line);
}
}
}
27. Network Programming: Clients27 www.corewebprogramming.com
A Class to Retrieve a Given
URL
public class UrlRetriever {
public static void main(String[] args) {
checkUsage(args);
StringTokenizer tok = new StringTokenizer(args[0]);
String protocol = tok.nextToken(":");
checkProtocol(protocol);
String host = tok.nextToken(":/");
String uri;
int port = 80;
try {
uri = tok.nextToken("");
if (uri.charAt(0) == ':') {
tok = new StringTokenizer(uri);
port = Integer.parseInt(tok.nextToken(":/"));
uri = tok.nextToken("");
}
} catch(NoSuchElementException nsee) {
uri = "/";
}
28. Network Programming: Clients28 www.corewebprogramming.com
A Class to Retrieve a Given
URL (Continued)
UriRetriever uriClient =
new UriRetriever(host, port, uri);
uriClient.connect();
}
/** Warn user if they forgot the URL. */
private static void checkUsage(String[] args) {
if (args.length != 1) {
System.out.println("Usage: UrlRetriever <URL>");
System.exit(-1);
}
}
/** Tell user that this can only handle HTTP. */
private static void checkProtocol(String protocol) {
if (!protocol.equals("http")) {
System.out.println("Don't understand protocol "
+ protocol);
System.exit(-1);
}
}}
29. Network Programming: Clients29 www.corewebprogramming.com
UrlRetriever in Action
• No explicit port number
Prompt> java UrlRetriever
http://www.microsoft.com/netscape-beats-ie.html
> HTTP/1.0 404 Object Not Found
> Content-Type: text/html
>
> <body><h1>HTTP/1.0 404 Object Not Found
> </h1></body>
30. Network Programming: Clients30 www.corewebprogramming.com
UrlRetriever in Action
(Continued)
• Explicit port number
Prompt> java UrlRetriever
http://home.netscape.com:80/ie-beats-netscape.html
> HTTP/1.0 404 Not found
> Server: Netscape-Enterprise/2.01
> Date: Wed, 11 Jul 2001 21:17:50 GMT
> Content-length: 207
> Content-type: text/html
>
> <TITLE>Not Found</TITLE><H1>Not Found</H1> The requested
object does not exist on this server. The link you
followed is either outdated, inaccurate, or the server
has been instructed not to let you have it.
31. Network Programming: Clients31 www.corewebprogramming.com
Writing a Web Browser
• Wow! We just wrote a Web browser in 3
pages of code.
– Didn't format the HTML, but still not bad for 3 pages
– But we can do even better…
32. Network Programming: Clients32 www.corewebprogramming.com
Browser in 1 Page: Using URL
public class UrlRetriever2 {
public static void main(String[] args) {
try {
URL url = new URL(args[0]);
BufferedReader in = new BufferedReader(
new InputStreamReader(
url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println("> " + line);
}
in.close();
} catch(MalformedURLException mue) { // URL c'tor
System.out.println(args[0] + "is an invalid URL: "
+ mue);
} catch(IOException ioe) { // Stream constructors
System.out.println("IOException: " + ioe);
}
}
}
33. Network Programming: Clients33 www.corewebprogramming.com
UrlRetriever2 in Action
Prompt> java UrlRetriever2 http://www.whitehouse.gov/
> <HTML>
> <HEAD>
> <TITLE>Welcome To The White House</TITLE>
> </HEAD>
> ... Remainder of HTML document omitted ...
> </HTML>
34. Network Programming: Clients34 www.corewebprogramming.com
Useful URL Methods
• openConnection
– Yields a URLConnection which establishes a connection to
host specified by the URL
– Used to retrieve header lines and to supply data to the HTTP
server
• openInputStream
– Returns the connection’s input stream for reading
• toExernalForm
– Gives the string representation of the URL
• getRef, getFile, getHost, getProtocol, getPort
– Returns the different components of the URL
35. Network Programming: Clients35 www.corewebprogramming.com
Using the URL Methods:
Example
import java.net.*;
public class UrlTest {
public static void main(String[] args) {
if (args.length == 1) {
try {
URL url = new URL(args[0]);
System.out.println
("URL: " + url.toExternalForm() + "n" +
" File: " + url.getFile() + "n" +
" Host: " + url.getHost() + "n" +
" Port: " + url.getPort() + "n" +
" Protocol: " + url.getProtocol() + "n" +
" Reference: " + url.getRef());
} catch(MalformedURLException mue) {
System.out.println("Bad URL.");
}
} else
System.out.println("Usage: UrlTest <URL>");
}
}
36. Network Programming: Clients36 www.corewebprogramming.com
Using the URL Methods, Result
> java UrlTest http://www.irs.gov/mission/#squeezing-them-dry
URL: http://www.irs.gov/mission/#squeezing-them-dry
File: /mission/
Host: www.irs.gov
Port: -1
Protocol: http
Reference: squeezing-them-dry
Note: If the port is not explicitly stated in the URL, then the
standard port for the protocol is assumed and getPort returns –1
37. Network Programming: Clients37 www.corewebprogramming.com
A Real Browser Using Swing
• The JEditorPane class has builtin support for
HTTP and HTML
38. Network Programming: Clients38 www.corewebprogramming.com
Browser in Swing: Code
import javax.swing.*;
import javax.swing.event.*;
...
public class Browser extends JFrame implements HyperlinkListener,
ActionListener {
private JEditorPane htmlPane;
...
public Browser(String initialURL) {
...
try {
htmlPane = new JEditorPane(initialURL);
htmlPane.setEditable(false);
htmlPane.addHyperlinkListener(this);
JScrollPane scrollPane = new JScrollPane(htmlPane);
getContentPane().add(scrollPane, BorderLayout.CENTER);
} catch(IOException ioe) {
warnUser("Can't build HTML pane for " + initialURL
+ ": " + ioe);
}
40. Network Programming: Clients40 www.corewebprogramming.com
Browser in Swing (Continued)
...
public void hyperlinkUpdate(HyperlinkEvent event) {
if (event.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED) {
try {
htmlPane.setPage(event.getURL());
urlField.setText(event.getURL().toExternalForm());
} catch(IOException ioe) {
warnUser("Can't follow link to "
+ event.getURL().toExternalForm() +
": " + ioe);
}
}
}
41. Network Programming: Clients41 www.corewebprogramming.com
Summary
• Opening a socket requires a hostname
(or IP address) and port number
• A PrintWriter lets you send string data
– Use autoflush to send the full line after each println
• A BufferedReader allows you to read the input
one line at a time (readLine)
– The readLine method blocks until a response is sent
– For a typical GET request, after the HTTP server sends
the response the connection is closed and readLine
returns null
• StringTokenizer provides simple parsing
• The URL and URLConnection classes simplify
communication with Web servers