SlideShare a Scribd company logo
Tutorial 2 Network Programming in Java


Tutorial 2 Network Programming in Java

Objectives

Java network programming introduction

HTTP introduction

Java URL class for establishing HTTP connection




                                                   1
Tutorial 2 Network Programming in Java




1 Java network programming introduction

Java provides            java.net        package   to   support   network
programming.

1.1 Client and Server
    A client obtains a service via sending a request to a
     server
    A client initiates a connection, retrieves data, responds
     user input. For example, web browser, chat program
     (ICQ)
    A server provides a set of services, such as web server,
     time server, file server, chat server.

    A server responds to connection, receives requests for
     data from client, and delivers it to client.
    The protocol between client and server is the
     communication rule, for example FTP, SMTP, and
     HTTP.




                                                                        2
Tutorial 2 Network Programming in Java


         1.2 Socket

          We use socket to establish the connection between client
           and server.
          Socket identifies a connection using host address and port
           number.

          A socket is a bi-directional communication channel

          Java differentiates client sockets from server sockets.

             e.g. for client
                 Socket client=new Socket(“hostname”,portNumber);

                 for server
                 ServerSocket server=new SeverSocket(portNumber);

         


Client
                                                    port 13   Time Service


                                                    port 80    Web Service

                   Socket                         Socket

                                                                     Server


                                                                       3
Tutorial 2 Network Programming in Java



    Well known ports for server
     80 web server
     21 Ftp server
     13 Time server
     23 Telnet
     25 Email(SMTP)

1.3 The connection between server and client using
   socket

Socket Operations at Client Side
 create a client socket:
    Socket (host, port)
    s = new Socket (“java.sun.com”, 13)

 get input / output data streams out of the socket:
    in = new DataInputStream(s.getInputStream ());
      out = new DataOutputStream( s.getOutputStream());
      out = new PrintStream( s.getOutputStream());

 read from input / write to output data streams:
    String str = in.readLine();
    out.println ( “Echo:” + str + “r”);

 close the socket:
    s.close();




                                                          4
Tutorial 2 Network Programming in Java


Socket Operations at Server Side

A server is always waiting for being connected. It
need not initiate a connection to a host. So a server
socket need only specify its own port no.
 create a server socket:
    ServerSocket (port)
    ServerSocket s = new ServerSocket(8189);
 accept an incoming connection:
    Socket snew = s.accept ();
 get input / output data streams out of the socket for
  the incoming client:
      in = new DataInputStream(snew.getInputStream());
      out = new PrintStream(snew.getOutputStream());
 close the socket for the incoming client:
    snew.close();

1.4 Example : A web Client


import java.net.*;
import java.io.*;

class HttpClient {
     public static void main(String[] args ) {
          try {


Tutorial for CS5286 Algorithms&Tech for Web Search   5
Tutorial 2 Network Programming in Java


              Socket s = new
Socket(quot;www.cs.cityu.edu.hkquot;,80);
              DataInputStrea in = new
                             m
DataInputStream(s.getInputStream());
              PrintStream out=new
PrintStream(s.getOutputStream());
              out.println(quot;GET / HTTP/1.0quot;);
              out.println();
              String line;
              while ((line=in.readLine())!=null)
                   System.out.println(quot;> quot;+line);
              s.close();
          } catch (Exception e)
{ System.out.println(e);}
     }
}



2 HTTP introduction

HTTP( Hypertext Transfer Protocol) is an application
layer protocol , just like FTP, SMTP, etc. The WWW is
based on HTTP, for the communication rule between
the browser and web server is HTTP.
You can check following URL for detailed document about
HTTP . http://www.w3.org/Protocols/



Tutorial for CS5286 Algorithms&Tech for Web Search   6
Tutorial 2 Network Programming in Java


2.1 Overview

HTTP request
Format: Method URI HTTP Version

For example: GET / HTTP/1.0
There are three most important methods in HTTP 1.0 ,
include GET, PUT and HEAD


   To request a web page, a browser sends a web server an
    HTTP GET message

   To send data to a web server, a browser can use an
    HTTP POST message

   To get information about document size , modification
    date, but not document itself , you can use HTTP HEAD
    request.

And there are some other HTTP methods added in HTTP
1.1 , such as PUT, DELETE, OPTIONS, and TRACE.

Also client can send additional information about itself to
web server, such as browser type, operation system.

HTTP response



Tutorial for CS5286 Algorithms&Tech for Web Search     7
Tutorial 2 Network Programming in Java


         After receiving client’s request, web server will
         respond. It includes web server HTTP version, HTTP
         server status code for client’s request, and some
         information about document, such as Content-Length,
         Content-Type, Last-Modified date.

                                         2. browser sends     3. server fetches web
               1. user types or             GET URL to            page for URL
                  clicks URL                   server




                                         4. server sends
                                        web page data to
                                             browser
 5. browser
displays web
    page*

                                             internet




         Tutorial for CS5286 Algorithms&Tech for Web Search                   8
Tutorial 2 Network Programming in Java


2.2 Example

import java.net.*;
import java.io.*;

class HttpClient1 {
      public static void main(String[] args ) {
             try {
   Socket s = new Socket(quot;www.cs.cityu.edu.hkquot;, 80);
   DataInputStream in = new
DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
  out.println(quot;HEAD /index.html HTTP/1.0quot;);
                  out.println();
                  String line;
                  while ((line=in.readLine())!=null)
                        System.out.println(quot;> quot;+line);
                  s.close();
             } catch (Exception e) { System.out.println(e);}
      }
}




Tutorial for CS5286 Algorithms&Tech for Web Search         9
Tutorial 2 Network Programming in Java


2.3 URL: Uniform Resource Locator


    The URL standard defines a common way to refer to
     any web page, anywhere on the web

      format: protocol://web_server_name/page_name

       example: http://www.yahoo.com/index.html

      URLs are most commonly used in conjunction with
       the HTTP protocol to GET a URL, or POST data to a
       URL

    a URL can refer to many kinds of web page:
     plain text, formatted text (usually in HTML…),
     multimedia, database, ...


2.4 HTML: HypeText Markup Language


•Specific mark-up language used in the Web

•Many kinds of markups

–low-level appearance (font changes, lists)
–logical structure (title, headings)
–links to other documents
–embedded graphics
–meta-information (language)

Tutorial for CS5286 Algorithms&Tech for Web Search    10
Tutorial 2 Network Programming in Java


–and much more...


       A simple HTML file

   <HTML>
   <HEAD>
   <TITLE>
   A HTML to test applet
   </TITLE>
   </HEAD>
   <BODY>
   <applet    code=quot;HelloKitty2.classquot;               Width=quot;80quot;
   Height=quot;100quot;>
   </applet>
   </BODY>
   </HTML>




Tutorial for CS5286 Algorithms&Tech for Web Search         11
Tutorial 2 Network Programming in Java




3       Java URL class

Java provides URL class to make it much easier to deal
with HTTP connection. We don’t need to care about low
layer socket connection.

You can find detailed information about them on following
URL,
http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html

3.1 URL

Constructor
URL(String spec)
    Creates a URL object from the String representation.
URL(String protocol, String host, int port, String file)
    Creates a URL object from the specified protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
    Creates a URL object from the specified protocol, host, port number, file, and handler.
URL(String protocol, String host, String file)
    Creates a URL from the specified protocol name, host name, and file name.
URL(URL context, String spec)
    Creates a URL by parsing the given spec within a specified context.
URL(URL context, String spec, URLStreamHandler handler)
      Creates a URL by parsing the given spec with the specified handler wit in a specified
                                                                           h
context.


Excetption
MalformedURLException
     Thrown if you try to create a bogus URL
Usually means bad user input, so fail
gracefully and informatively


Tutorial for CS5286 Algorithms&Tech for Web Search                                   12
Tutorial 2 Network Programming in Java


accessor methods

getProtocol(), getHost(), getPort(),
getFile(), getRef()


openConnection()

public URLConnection openConnection() throws
IOException
    Returns a URLConnection object that
    represents a connection to the remote
    object referred to by the URL.
    If there is not already an open
    connection, the connection is opened by
    calling the openConnection method of the
    protocol handler for this URL.

OpenStream()
public final InputStream openStream() throws
IOException
Opens a connection to this URL and returns
an    InputStream     for    reading     from that
connection. This method is a shorthand for:
openConnection().getInputStream()

getContent
 public final Object getContent() throws IOException
 Returns the contents of this URL. This method is a shorthand for:
           openConnection().getContent()




Tutorial for CS5286 Algorithms&Tech for Web Search            13
Tutorial 2 Network Programming in Java


Example 1

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
         (quot;URL: quot; + url.toExternalForm() + quot;nquot; +
          quot; File: quot; + url.getFile() + quot;nquot; +
          quot; Host: quot; + url.getHost() + quot;nquot; +
          quot; Port: quot; + url.getPort() + quot;nquot; +
          quot; Protocol: quot; + url.getProtocol() + quot;nquot; +
          quot; Reference: quot; + url.getRef());
      } catch(MalformedURLException mue) {
        System.out.println(quot;Bad URL.quot;);
      }
    } else
      System.out.println(quot;Usage: UrlTest <URL>quot;);
  }
}




Tutorial for CS5286 Algorithms&Tech for Web Search     14
Tutorial 2 Network Programming in Java



Example 2 was given in Tutorial 1.
Using openStream()

Example 3 Using getContent()
import java.net.*;
import java.io.*;

public class UrlRetriever1 {
   public static void main(String[] args) {
   checkUsage(args);
   try {
       URL url=new URL(args[0]);

                                      DataInputStream   in=    new
DataInputStream((InputStream)url.getContent());
      String line;
      while ((line=in.readLine())!=null)
          System.out.println(line);
      in.close();
     } catch(MalformedURLException mue)
     { System.out.println(args[0]+quot;is an invalid URL:quot;+mue);
     } catch(IOException ioe) {
       System.out.println(quot;IOException: quot;+ioe);
     }
     }

     private static void checkUsage(String[] args) {
      if (args.length!=1) {
         System.out.println(quot;Usage: UrlRetriever2 <URL>quot;);
         System.exit(-1);
         }
         }
       }




Tutorial for CS5286 Algorithms&Tech for Web Search                   15
Tutorial 2 Network Programming in Java




4      Exercises

 Implement a HTTP server (Simulated) using
  ServerSocket.


   Using URL Class, write a http client to retrieve
    http://www.cs.cityu.edu.hk/index.html, and return the
    last modified date, Content-Length, Content-Type of this
    web page.




Tutorial for CS5286 Algorithms&Tech for Web Search     16

More Related Content

What's hot

Network Sockets
Network SocketsNetwork Sockets
Network Sockets
Peter R. Egli
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
elliando dias
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
elliando dias
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
Mostak Ahmed
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming Clients
Adil Jafri
 
Socket programming
Socket programmingSocket programming
Socket programming
Anurag Tomar
 
Socket programming
Socket programmingSocket programming
Socket programming
harsh_bca06
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
Avinash Varma Kalidindi
 
Socket programming
Socket programming Socket programming
Socket programming
Rajivarnan (Rajiv)
 
Sockets
SocketsSockets
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
VisualBee.com
 
Lecture10
Lecture10Lecture10
Lecture10
vantinhkhuc
 
HTTP
HTTPHTTP
Socket programming
Socket programmingSocket programming
Socket programming
Ujjwal Kumar
 
Sockets
SocketsSockets
Sockets
Rajesh Kumar
 
An Introduction to HTTP
An Introduction to HTTPAn Introduction to HTTP
An Introduction to HTTP
Keerthana Krishnan
 
Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Sockets
elliando dias
 
Networks lab
Networks labNetworks lab
Networks lab
svijiiii
 
Socket programing
Socket programingSocket programing
Socket programing
Pankil Agrawal
 

What's hot (19)

Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming Clients
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
Socket programming
Socket programming Socket programming
Socket programming
 
Sockets
SocketsSockets
Sockets
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Lecture10
Lecture10Lecture10
Lecture10
 
HTTP
HTTPHTTP
HTTP
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Sockets
SocketsSockets
Sockets
 
An Introduction to HTTP
An Introduction to HTTPAn Introduction to HTTP
An Introduction to HTTP
 
Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Sockets
 
Networks lab
Networks labNetworks lab
Networks lab
 
Socket programing
Socket programingSocket programing
Socket programing
 

Viewers also liked

Adjectives And Adverbs
Adjectives And AdverbsAdjectives And Adverbs
Adjectives And Adverbs
juliapn1980
 
2drug Prevention Ppt
2drug Prevention Ppt2drug Prevention Ppt
2drug Prevention Ppt
juliapn1980
 
Ancient Mexico
Ancient MexicoAncient Mexico
Ancient Mexico
juliapn1980
 
Ancient Greece
Ancient GreeceAncient Greece
Ancient Greece
juliapn1980
 
Adjectives And Adverbs
Adjectives And AdverbsAdjectives And Adverbs
Adjectives And Adverbs
juliapn1980
 
2ndeasysteps
2ndeasysteps2ndeasysteps
2ndeasysteps
juliapn1980
 
Adjectives And Adverbs2
Adjectives And Adverbs2Adjectives And Adverbs2
Adjectives And Adverbs2
juliapn1980
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
Luminary Labs
 

Viewers also liked (8)

Adjectives And Adverbs
Adjectives And AdverbsAdjectives And Adverbs
Adjectives And Adverbs
 
2drug Prevention Ppt
2drug Prevention Ppt2drug Prevention Ppt
2drug Prevention Ppt
 
Ancient Mexico
Ancient MexicoAncient Mexico
Ancient Mexico
 
Ancient Greece
Ancient GreeceAncient Greece
Ancient Greece
 
Adjectives And Adverbs
Adjectives And AdverbsAdjectives And Adverbs
Adjectives And Adverbs
 
2ndeasysteps
2ndeasysteps2ndeasysteps
2ndeasysteps
 
Adjectives And Adverbs2
Adjectives And Adverbs2Adjectives And Adverbs2
Adjectives And Adverbs2
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 

Similar to T2

java networking
 java networking java networking
java networking
Waheed Warraich
 
A.java
A.javaA.java
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
Sockets
SocketsSockets
Sockets
sivindia
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
Tushar B Kute
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
arnold 7490
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
hanneloremccaffery
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
 
Java 1
Java 1Java 1
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
WebStackAcademy
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
smile790243
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
kacie8xcheco
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
VannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
alfredacavx97
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
Mousmi Pawar
 
28 networking
28  networking28  networking
28 networking
Ravindra Rathore
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
Hemant Chetwani
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
Adil Jafri
 
1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel
AgripinaBeaulieuyw
 

Similar to T2 (20)

java networking
 java networking java networking
java networking
 
A.java
A.javaA.java
A.java
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Sockets
SocketsSockets
Sockets
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Java 1
Java 1Java 1
Java 1
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
28 networking
28  networking28  networking
28 networking
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel
 

Recently uploaded

The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
Kavitha Krishnan
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 

Recently uploaded (20)

The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 

T2

  • 1. Tutorial 2 Network Programming in Java Tutorial 2 Network Programming in Java Objectives Java network programming introduction HTTP introduction Java URL class for establishing HTTP connection 1
  • 2. Tutorial 2 Network Programming in Java 1 Java network programming introduction Java provides java.net package to support network programming. 1.1 Client and Server  A client obtains a service via sending a request to a server  A client initiates a connection, retrieves data, responds user input. For example, web browser, chat program (ICQ)  A server provides a set of services, such as web server, time server, file server, chat server.  A server responds to connection, receives requests for data from client, and delivers it to client.  The protocol between client and server is the communication rule, for example FTP, SMTP, and HTTP. 2
  • 3. Tutorial 2 Network Programming in Java 1.2 Socket  We use socket to establish the connection between client and server.  Socket identifies a connection using host address and port number.  A socket is a bi-directional communication channel  Java differentiates client sockets from server sockets. e.g. for client Socket client=new Socket(“hostname”,portNumber); for server ServerSocket server=new SeverSocket(portNumber);  Client port 13 Time Service port 80 Web Service Socket Socket Server 3
  • 4. Tutorial 2 Network Programming in Java  Well known ports for server 80 web server 21 Ftp server 13 Time server 23 Telnet 25 Email(SMTP) 1.3 The connection between server and client using socket Socket Operations at Client Side  create a client socket: Socket (host, port) s = new Socket (“java.sun.com”, 13)  get input / output data streams out of the socket: in = new DataInputStream(s.getInputStream ()); out = new DataOutputStream( s.getOutputStream()); out = new PrintStream( s.getOutputStream());  read from input / write to output data streams: String str = in.readLine(); out.println ( “Echo:” + str + “r”);  close the socket: s.close(); 4
  • 5. Tutorial 2 Network Programming in Java Socket Operations at Server Side A server is always waiting for being connected. It need not initiate a connection to a host. So a server socket need only specify its own port no.  create a server socket: ServerSocket (port) ServerSocket s = new ServerSocket(8189);  accept an incoming connection: Socket snew = s.accept ();  get input / output data streams out of the socket for the incoming client: in = new DataInputStream(snew.getInputStream()); out = new PrintStream(snew.getOutputStream());  close the socket for the incoming client: snew.close(); 1.4 Example : A web Client import java.net.*; import java.io.*; class HttpClient { public static void main(String[] args ) { try { Tutorial for CS5286 Algorithms&Tech for Web Search 5
  • 6. Tutorial 2 Network Programming in Java Socket s = new Socket(quot;www.cs.cityu.edu.hkquot;,80); DataInputStrea in = new m DataInputStream(s.getInputStream()); PrintStream out=new PrintStream(s.getOutputStream()); out.println(quot;GET / HTTP/1.0quot;); out.println(); String line; while ((line=in.readLine())!=null) System.out.println(quot;> quot;+line); s.close(); } catch (Exception e) { System.out.println(e);} } } 2 HTTP introduction HTTP( Hypertext Transfer Protocol) is an application layer protocol , just like FTP, SMTP, etc. The WWW is based on HTTP, for the communication rule between the browser and web server is HTTP. You can check following URL for detailed document about HTTP . http://www.w3.org/Protocols/ Tutorial for CS5286 Algorithms&Tech for Web Search 6
  • 7. Tutorial 2 Network Programming in Java 2.1 Overview HTTP request Format: Method URI HTTP Version For example: GET / HTTP/1.0 There are three most important methods in HTTP 1.0 , include GET, PUT and HEAD  To request a web page, a browser sends a web server an HTTP GET message  To send data to a web server, a browser can use an HTTP POST message  To get information about document size , modification date, but not document itself , you can use HTTP HEAD request. And there are some other HTTP methods added in HTTP 1.1 , such as PUT, DELETE, OPTIONS, and TRACE. Also client can send additional information about itself to web server, such as browser type, operation system. HTTP response Tutorial for CS5286 Algorithms&Tech for Web Search 7
  • 8. Tutorial 2 Network Programming in Java After receiving client’s request, web server will respond. It includes web server HTTP version, HTTP server status code for client’s request, and some information about document, such as Content-Length, Content-Type, Last-Modified date. 2. browser sends 3. server fetches web 1. user types or GET URL to page for URL clicks URL server 4. server sends web page data to browser 5. browser displays web page* internet Tutorial for CS5286 Algorithms&Tech for Web Search 8
  • 9. Tutorial 2 Network Programming in Java 2.2 Example import java.net.*; import java.io.*; class HttpClient1 { public static void main(String[] args ) { try { Socket s = new Socket(quot;www.cs.cityu.edu.hkquot;, 80); DataInputStream in = new DataInputStream(s.getInputStream()); PrintStream out=new PrintStream(s.getOutputStream()); out.println(quot;HEAD /index.html HTTP/1.0quot;); out.println(); String line; while ((line=in.readLine())!=null) System.out.println(quot;> quot;+line); s.close(); } catch (Exception e) { System.out.println(e);} } } Tutorial for CS5286 Algorithms&Tech for Web Search 9
  • 10. Tutorial 2 Network Programming in Java 2.3 URL: Uniform Resource Locator  The URL standard defines a common way to refer to any web page, anywhere on the web  format: protocol://web_server_name/page_name example: http://www.yahoo.com/index.html  URLs are most commonly used in conjunction with the HTTP protocol to GET a URL, or POST data to a URL  a URL can refer to many kinds of web page: plain text, formatted text (usually in HTML…), multimedia, database, ... 2.4 HTML: HypeText Markup Language •Specific mark-up language used in the Web •Many kinds of markups –low-level appearance (font changes, lists) –logical structure (title, headings) –links to other documents –embedded graphics –meta-information (language) Tutorial for CS5286 Algorithms&Tech for Web Search 10
  • 11. Tutorial 2 Network Programming in Java –and much more...  A simple HTML file <HTML> <HEAD> <TITLE> A HTML to test applet </TITLE> </HEAD> <BODY> <applet code=quot;HelloKitty2.classquot; Width=quot;80quot; Height=quot;100quot;> </applet> </BODY> </HTML> Tutorial for CS5286 Algorithms&Tech for Web Search 11
  • 12. Tutorial 2 Network Programming in Java 3 Java URL class Java provides URL class to make it much easier to deal with HTTP connection. We don’t need to care about low layer socket connection. You can find detailed information about them on following URL, http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html 3.1 URL Constructor URL(String spec) Creates a URL object from the String representation. URL(String protocol, String host, int port, String file) Creates a URL object from the specified protocol, host, port number, and file. URL(String protocol, String host, int port, String file, URLStreamHandler handler) Creates a URL object from the specified protocol, host, port number, file, and handler. URL(String protocol, String host, String file) Creates a URL from the specified protocol name, host name, and file name. URL(URL context, String spec) Creates a URL by parsing the given spec within a specified context. URL(URL context, String spec, URLStreamHandler handler) Creates a URL by parsing the given spec with the specified handler wit in a specified h context. Excetption MalformedURLException Thrown if you try to create a bogus URL Usually means bad user input, so fail gracefully and informatively Tutorial for CS5286 Algorithms&Tech for Web Search 12
  • 13. Tutorial 2 Network Programming in Java accessor methods getProtocol(), getHost(), getPort(), getFile(), getRef() openConnection() public URLConnection openConnection() throws IOException Returns a URLConnection object that represents a connection to the remote object referred to by the URL. If there is not already an open connection, the connection is opened by calling the openConnection method of the protocol handler for this URL. OpenStream() public final InputStream openStream() throws IOException Opens a connection to this URL and returns an InputStream for reading from that connection. This method is a shorthand for: openConnection().getInputStream() getContent public final Object getContent() throws IOException Returns the contents of this URL. This method is a shorthand for: openConnection().getContent() Tutorial for CS5286 Algorithms&Tech for Web Search 13
  • 14. Tutorial 2 Network Programming in Java Example 1 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 (quot;URL: quot; + url.toExternalForm() + quot;nquot; + quot; File: quot; + url.getFile() + quot;nquot; + quot; Host: quot; + url.getHost() + quot;nquot; + quot; Port: quot; + url.getPort() + quot;nquot; + quot; Protocol: quot; + url.getProtocol() + quot;nquot; + quot; Reference: quot; + url.getRef()); } catch(MalformedURLException mue) { System.out.println(quot;Bad URL.quot;); } } else System.out.println(quot;Usage: UrlTest <URL>quot;); } } Tutorial for CS5286 Algorithms&Tech for Web Search 14
  • 15. Tutorial 2 Network Programming in Java Example 2 was given in Tutorial 1. Using openStream() Example 3 Using getContent() import java.net.*; import java.io.*; public class UrlRetriever1 { public static void main(String[] args) { checkUsage(args); try { URL url=new URL(args[0]); DataInputStream in= new DataInputStream((InputStream)url.getContent()); String line; while ((line=in.readLine())!=null) System.out.println(line); in.close(); } catch(MalformedURLException mue) { System.out.println(args[0]+quot;is an invalid URL:quot;+mue); } catch(IOException ioe) { System.out.println(quot;IOException: quot;+ioe); } } private static void checkUsage(String[] args) { if (args.length!=1) { System.out.println(quot;Usage: UrlRetriever2 <URL>quot;); System.exit(-1); } } } Tutorial for CS5286 Algorithms&Tech for Web Search 15
  • 16. Tutorial 2 Network Programming in Java 4 Exercises  Implement a HTTP server (Simulated) using ServerSocket.  Using URL Class, write a http client to retrieve http://www.cs.cityu.edu.hk/index.html, and return the last modified date, Content-Length, Content-Type of this web page. Tutorial for CS5286 Algorithms&Tech for Web Search 16