SlideShare une entreprise Scribd logo
1  sur  39
Télécharger pour lire hors ligne
Java Socket Programming
Keyboard Access in Java
• Java provides access to the standard input stream
  (stdin)
• java.lang.System.in
  –   ‘java.lang is the package
  –   ‘System’ is the class
  –   ‘in’ is an object of type InputStream
  –   InputStream is defined in the java.io package
Keyboard Access in Java


int cc;
While(true) {
  try {
     cc=System.in.read();
  } catch (IOException ex) {}
  System.out.write(cc);
}
java.io.InputStreamReader
• This class provides a character interface to input
  stream (also converts to unicode characters)
int cc;
InputStreamReader inkey;
Inkey=new InputStreamReader(System.in);

While(true) {
  try {
      cc = inkey.read();
  } catch (IOException ex) {}
  System.out.print(cc);
}
java.io.BufferedReader
• Provides a buffer for the input stream—can be
  accessed on a line by line basis
String s;
InputStreamReader inkey;
BufferedReader bufkey;
inkey=new InputStreamReader(System.in);
bufkey=new BufferedReader(inkey);

While(true) {
  s=bufkey.readLine();
  System.out.println(s);
}
Lines of text
                       (strings)


  java.io.BufferedReader
                       Unicode character
                       stream

java.io.InputStreamReader
                       Byte stream from
                       keyboard

     java.lang.System.in


           Keyboard
File access in Java
• java.io.File
  – This allows you to open a file
  – Eg. File infile = new File(“Blah.txt”);
• java.io.FileInputStream
  – This sets up an input stream from the file
     • FileInputStream instream = new
       FileInputStream(infile);
  – FileInputStream can open a file directly…
     • FileInputStream instream = new
       FileInputStream(“Blah.txt”);
File access in Java
FileInputStream instream;
instream = new FileInputStream(“blah.txt”)
int cc;
while ((cc=instream.read() != -1) {
  System.out.print((char)cc);
}
File Access in Java

• FileInputStream is a subclass of InputStream.
• Recall that the System.in object, used for
  keyboard input is also of class InputStream.
• This means that we can use InputStreamReader
  and BufferedReader just as with the keyboard
import java.io.*;

class uppercase {
  public static void main(String [] args) {
    FileInputStream instream;
    FileOutputStream outstream;
    BufferedReader bufinstream;
    BufferedWriter bufoutstream;

    if (args.length != 2) {
      System.out.println(“usage: file <infile> “
        +”<outfile>”);
      System.exit(1);
    }

    String infile = args[0];
    String outfile = args[1];
try {
         instream = new FileInputStream(infile);
         outstream = new FileOutputStream(outfile);
         bufinstream = new BufferedReader(new
                  InputStreamReader(instream));
         bufoutstream = new BufferedWriter(new
                  OutputStreamWriter(outstream));

          String c;
          String d;
          while ((c=bufinstream.readLine()!=null) {
            d = c.toUpperCase();
            bufoutstream.write(d, 0, d.length());
            bufoutstream.newLine();
          }
          bufinstream.close();
          bufoutstream.close();
        } catch (IOException e) {
          System.err.println(“oops”);
        }
    }
}
mhall@goblin:~>more blah.txt
test1
test2
Blahblahblah

mhall@goblin:~>java uppercase blah.txt blah2.txt
mhall@goblin:~>cat blah2.txt
TEST1
TEST2
BLAHBLAHBLAH
mhall@goblin:~>
My uppercase code
                        Lines of text
                        (strings)


  java.io.Bufferedreader
                         Unicode character
                         stream

java.io.InputStreamReader
                         Byte stream from
                         file

java.file.FileInputStream


               File
The process of using a file

     Open file using some
      unique identifier




       Read and write to
       and from the file




 Close the file
Accessing a computer across a
                     network
            Connect to computer
             using some unique
                  identifier




             Read and write to
           and from the computer




   Close the connection
Sockets - connecting to other
                             computers
• When connecting to another computer you use a
  ‘socket’.
  – analogous to a ‘file handle’ used when accessing
    files
  – When opening a file you uniquely identify it by its
    file name. When connecting to a computer you
    uniquely identify it with its IP number
Addressing Computers

• An IP number is four numbers (each between 0
  and 255) separated by a ‘.’ Eg. Goblin’s IP is
  130.217.208.41
  – However, because numbers are difficult to remember,
    the network provides a service that associates names
    with numbers.
     • Eg goblin.cs.waikato.ac.nz : 130.217.208.41
Ports — connecting to programs on
        other computers over a network

• Using a unique number we can identify a
  computer to connect to
  – However, computers have many programs running
    on them
  – We identify which program to communicate with by
    using a port number
  – Common networking programs (such as telnet, ftp
    and WWW services) are always on the same port.
    These ports are called “well known”
  – Telnet is on port 23, FTP on port 21, WWW
    services are on port 80, etc.
File /etc/services
tcpmux     1/tcp    # TCP port service multiplexer
echo       7/tcp
echo       7/udp
discard    9/tcp    sink null
discard    9/udp    sink null
systat     11/tcp   users
daytime    13/tcp
daytime    13/udp
netstat    15/tcp
qotd       17/tcp   quote
msp        18/tcp   # message send protocol
msp        18/udp   # message send protocol
chargen    19/tcp   ttytst source
chargen    19/udp   ttytst source
ftp-data   20/tcp   # File Transfer [Default Data]
ftp-data   20/udp   # File Transfer [Default Data]
ftp        21/tcp   # File Transfer [Control]
ftp        21/udp   # File Transfer [Control]
ssh        22/tcp   # Secure Shell Login
ssh        22/udp   # Secure Shell Login
telnet     23/tcp
telnet     23/udp
Sockets in Java
• Java’s networking facilities are provided in the java.net
  package
   – To make a connection to another machine we must first know
     its IP number—this is done by the InetAddress class
      • InetAddress goblinsIP = InetAddress.getByName(“goblin”);
   – Now we can open a socket
      • Socket mysocket = new Socket(goblinsIP, 23);
   – This would connect to the telnet port on goblin
Sockets in Java

• The following methods return input and output streams that you
  can use to read and write to the socket, just like a file
       • mysocket.getInputStream();
       • Mysocket.getOutputStream();
   – Eg:
       • InputStreamReader in = new
         InputStreamReader(mysocket.getInputStream());
       • OutputStreamWriter out = new
         OutputStreamWriter(mysocket.getOutputStream());
Echoed response
                         Lines of text
                         (strings)


  java.io.BufferedReader
                         Unicode character
                         stream

java.io.InputStreamReader
                         Byte stream from
                         socket

       java.net.Socket


           Network
Echo Client
• There is a program (also known as a service) on most networked
  machines that echoes back what you write to it. This program
  connects to that echo service (port 7) and writes and reads to/from it


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

     public class EchoClient {
       public static void main(String [] args)
         throws IOException {
         Socket echoSocket = null;
         PrintWriter out = null;
         BufferedReader in = null;
Echo Client...

try {
     InetAddress goblinsIP =
       InetAddress.getByName(“goblin”);

    echoSocket =
      new Socket(goblinsIP, 7);
    out = new PrintWriter(echoSocket.
          getOutputStream(), true);
    in = new BufferedReader(new
      InputStreamReader(echoSocket.
                        getInputStream());
Echo Client


} catch (UnknownHostException e) {
      System.err.println(“Don’t know about “
        +”host: goblin.”);
      System.exit(1);
    } catch (IOException e) {
      System.err.println(“Couldn’t get I/O “
        +”for connection to: goblin.”);
      System.exit(1);
    }
Echo Client...
 BufferedReader stdIn = new
      BufferedReader(new
          InputStreamReader(System.in));
    String userInput;

    while((userInput = stdIn.readLine())
           != null) {
        out.println(userInput);
        System.out.println(“echo: “
          + in.readLine());
     }
 out.close();
    in.close();
    stdIn.close();
    echoSocket.close();
  }
}
Echo Client in use.


mhall@goblin:~> java EchoClient
Boo!
echo: Boo!
Hello there
echo: Hello there
Quit
echo: Quit
Clients and Servers…
• So far we have considered a ‘client’ program
  that connects through a socket to a service (or
  server)
                  Connect



                    Write



                     Read



                    Close
Clients and Servers…
• Consider the actions of the server at the other
  end
                      Listen



                     Accept



                      Read



                      Write



                      Close
Clients and Servers…
• Java provides the class ServerSocket which listens to
  connections. Eg:
   – ServerSocket myserver = new ServerSocket(4420);
   – This sets up a ServerSocket to listen on port 4420
   – Now wait for a connection using the “accept” method. This
     method returns a reference to a regular socket that can be
     used to read and write to the connection client
   – Socket theClient = myserver.accept();
   – The socket “theClient” can now be used tp read and write to
     the connecting client in the usual way
Echo Server…
import java.io.*;
import java.net.*;

public class EchoServer {
  public static void main(String [] args)
    throws IOException {

   ServerSocket myserver = null;
   try {
     myserver = new ServerSocket(4444);
   } catch (IOException e) {
     System.out.println(“Could not listen “
       +”on port: 4444.”);
     System.exit(1);
   }
Echo Server...
Socket theclient = null;
    try {
      theclient = myserver.accept();
    } catch (IOException e) {
      System.err.pritnln(“Accept failed.”);
      System.exit(1);
    }

   PrintWriter out = new
     PrintWriter(theclient.getOutputStream(),
                 true));
   BufferedReader in = new
     BufferedReader(new
       InputStreamReader(theclient.
                         getInputStream()));
Echo Server…
        String inputLine, outputLine;

        while((inputLine=in.readLine()) != null) {
          outputLine = inputLine + “ :-)”;
          out.println(outputLine);
          if (inputLine.equals(“Bye.”)) {
            break;
          }
        }

        out.close();
        in.close();
        theclient.close();
        myserver.close();
    }
}
Request for connection
                  ServerSocket     Client Program
ServerSocket
                  creates socket


               Socket                       Socket




   Port 23                                 Port X


                                              Request for
                         Network              connection
Server and Client Communicate

                       Server Program             Client Program

ServerSocket

                               Socket                      Socket




          Port 23                                         Port X


                                        Network
Multiple Connections…
• Consider the case where multiple clients are
  connected to the same service. Eg. Multiple
  telnet connections to goblin
• How do sockets deal with this?
Request for Connection

                           ServerSocket
ServerSocket               allocates a new
                           socket
                                     New Socket



    Port 23

               Request for
               connection from
               client
Request for Another Connection

                                                          Server code
ServerSocket
allocates another
                        ServerSocket
socket

  New Socket                                              Established
                                                          Socket

                            Port 23


  Another request for                  Client reads and
  connection                           writes to server
Multiple Connections...

•The port records what clients have connected and
diverts interaction to the appropriate socket.
•A client is identified by:
– IP number and Port number!
•When a socket is created on the client machine it is
allocated a local port number as well. This is the port
that the server uses to write to the client

Contenu connexe

Tendances

Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programmingelliando dias
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket basedMukesh Tekwani
 
Socket programming
Socket programmingSocket programming
Socket programmingAnurag Tomar
 
Socket Programming
Socket ProgrammingSocket Programming
Socket ProgrammingCEC Landran
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 

Tendances (20)

Sockets
SocketsSockets
Sockets
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
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
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
java networking
 java networking java networking
java networking
 
socket programming
socket programming socket programming
socket programming
 
Socket programming
Socket programming Socket programming
Socket programming
 
Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket based
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Networking in java
Networking in javaNetworking in java
Networking in java
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 

En vedette

Present Continuous
Present ContinuousPresent Continuous
Present Continuouslupitath09
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without PagingEmery Berger
 
Copenhagen Open For Connections Dias
Copenhagen Open For Connections DiasCopenhagen Open For Connections Dias
Copenhagen Open For Connections DiasWonderful Copenhagen
 
Open and online: connections, community and reality
Open and online: connections, community and reality Open and online: connections, community and reality
Open and online: connections, community and reality Catherine Cronin
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programmingSonam Sharma
 
Insert a Page Number in the Running Head
Insert a Page Number in the Running HeadInsert a Page Number in the Running Head
Insert a Page Number in the Running HeadAmy Lynn Hess
 
Presentiaon task sheduling first come first serve FCFS
Presentiaon  task sheduling first come first serve FCFSPresentiaon  task sheduling first come first serve FCFS
Presentiaon task sheduling first come first serve FCFSAhmed Salah
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-asciiirdginfo
 
Process' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxProcess' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxVarun Mahajan
 
C scan scheduling 50 2
C scan scheduling 50 2C scan scheduling 50 2
C scan scheduling 50 2myrajendra
 
3장. Garbage Collection
3장. Garbage Collection3장. Garbage Collection
3장. Garbage Collection김 한도
 
Look scheduling.51
Look scheduling.51Look scheduling.51
Look scheduling.51myrajendra
 
Sstf scheduling.50
Sstf scheduling.50Sstf scheduling.50
Sstf scheduling.50myrajendra
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection TechniquesAn Khuong
 
Fcfs scheduling
Fcfs schedulingFcfs scheduling
Fcfs schedulingmyrajendra
 

En vedette (20)

Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
Present Continuous
Present ContinuousPresent Continuous
Present Continuous
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without Paging
 
Copenhagen Open For Connections Dias
Copenhagen Open For Connections DiasCopenhagen Open For Connections Dias
Copenhagen Open For Connections Dias
 
Open and online: connections, community and reality
Open and online: connections, community and reality Open and online: connections, community and reality
Open and online: connections, community and reality
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
 
Insert a Page Number in the Running Head
Insert a Page Number in the Running HeadInsert a Page Number in the Running Head
Insert a Page Number in the Running Head
 
Presentiaon task sheduling first come first serve FCFS
Presentiaon  task sheduling first come first serve FCFSPresentiaon  task sheduling first come first serve FCFS
Presentiaon task sheduling first come first serve FCFS
 
The Look Of Love
The Look Of LoveThe Look Of Love
The Look Of Love
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-ascii
 
Ascii codes
Ascii codesAscii codes
Ascii codes
 
Process' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxProcess' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/Linux
 
C scan scheduling 50 2
C scan scheduling 50 2C scan scheduling 50 2
C scan scheduling 50 2
 
3장. Garbage Collection
3장. Garbage Collection3장. Garbage Collection
3장. Garbage Collection
 
Paging-R.D.Sivakumar
Paging-R.D.SivakumarPaging-R.D.Sivakumar
Paging-R.D.Sivakumar
 
Look scheduling.51
Look scheduling.51Look scheduling.51
Look scheduling.51
 
Sstf scheduling.50
Sstf scheduling.50Sstf scheduling.50
Sstf scheduling.50
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection Techniques
 
Fcfs scheduling
Fcfs schedulingFcfs scheduling
Fcfs scheduling
 
message passing
 message passing message passing
message passing
 

Similaire à Java sockets

Similaire à Java sockets (20)

Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Java I/O
Java I/OJava I/O
Java I/O
 
JAVA (UNIT 3)
JAVA (UNIT 3)JAVA (UNIT 3)
JAVA (UNIT 3)
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java 1
Java 1Java 1
Java 1
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Lecture10
Lecture10Lecture10
Lecture10
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming Clients
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
A.java
A.javaA.java
A.java
 
Java adv
Java advJava adv
Java adv
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 

Dernier

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Dernier (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Java sockets

  • 2. Keyboard Access in Java • Java provides access to the standard input stream (stdin) • java.lang.System.in – ‘java.lang is the package – ‘System’ is the class – ‘in’ is an object of type InputStream – InputStream is defined in the java.io package
  • 3. Keyboard Access in Java int cc; While(true) { try { cc=System.in.read(); } catch (IOException ex) {} System.out.write(cc); }
  • 4. java.io.InputStreamReader • This class provides a character interface to input stream (also converts to unicode characters) int cc; InputStreamReader inkey; Inkey=new InputStreamReader(System.in); While(true) { try { cc = inkey.read(); } catch (IOException ex) {} System.out.print(cc); }
  • 5. java.io.BufferedReader • Provides a buffer for the input stream—can be accessed on a line by line basis String s; InputStreamReader inkey; BufferedReader bufkey; inkey=new InputStreamReader(System.in); bufkey=new BufferedReader(inkey); While(true) { s=bufkey.readLine(); System.out.println(s); }
  • 6. Lines of text (strings) java.io.BufferedReader Unicode character stream java.io.InputStreamReader Byte stream from keyboard java.lang.System.in Keyboard
  • 7. File access in Java • java.io.File – This allows you to open a file – Eg. File infile = new File(“Blah.txt”); • java.io.FileInputStream – This sets up an input stream from the file • FileInputStream instream = new FileInputStream(infile); – FileInputStream can open a file directly… • FileInputStream instream = new FileInputStream(“Blah.txt”);
  • 8. File access in Java FileInputStream instream; instream = new FileInputStream(“blah.txt”) int cc; while ((cc=instream.read() != -1) { System.out.print((char)cc); }
  • 9. File Access in Java • FileInputStream is a subclass of InputStream. • Recall that the System.in object, used for keyboard input is also of class InputStream. • This means that we can use InputStreamReader and BufferedReader just as with the keyboard
  • 10. import java.io.*; class uppercase { public static void main(String [] args) { FileInputStream instream; FileOutputStream outstream; BufferedReader bufinstream; BufferedWriter bufoutstream; if (args.length != 2) { System.out.println(“usage: file <infile> “ +”<outfile>”); System.exit(1); } String infile = args[0]; String outfile = args[1];
  • 11. try { instream = new FileInputStream(infile); outstream = new FileOutputStream(outfile); bufinstream = new BufferedReader(new InputStreamReader(instream)); bufoutstream = new BufferedWriter(new OutputStreamWriter(outstream)); String c; String d; while ((c=bufinstream.readLine()!=null) { d = c.toUpperCase(); bufoutstream.write(d, 0, d.length()); bufoutstream.newLine(); } bufinstream.close(); bufoutstream.close(); } catch (IOException e) { System.err.println(“oops”); } } }
  • 12. mhall@goblin:~>more blah.txt test1 test2 Blahblahblah mhall@goblin:~>java uppercase blah.txt blah2.txt mhall@goblin:~>cat blah2.txt TEST1 TEST2 BLAHBLAHBLAH mhall@goblin:~>
  • 13. My uppercase code Lines of text (strings) java.io.Bufferedreader Unicode character stream java.io.InputStreamReader Byte stream from file java.file.FileInputStream File
  • 14. The process of using a file Open file using some unique identifier Read and write to and from the file Close the file
  • 15. Accessing a computer across a network Connect to computer using some unique identifier Read and write to and from the computer Close the connection
  • 16. Sockets - connecting to other computers • When connecting to another computer you use a ‘socket’. – analogous to a ‘file handle’ used when accessing files – When opening a file you uniquely identify it by its file name. When connecting to a computer you uniquely identify it with its IP number
  • 17. Addressing Computers • An IP number is four numbers (each between 0 and 255) separated by a ‘.’ Eg. Goblin’s IP is 130.217.208.41 – However, because numbers are difficult to remember, the network provides a service that associates names with numbers. • Eg goblin.cs.waikato.ac.nz : 130.217.208.41
  • 18. Ports — connecting to programs on other computers over a network • Using a unique number we can identify a computer to connect to – However, computers have many programs running on them – We identify which program to communicate with by using a port number – Common networking programs (such as telnet, ftp and WWW services) are always on the same port. These ports are called “well known” – Telnet is on port 23, FTP on port 21, WWW services are on port 80, etc.
  • 19. File /etc/services tcpmux 1/tcp # TCP port service multiplexer echo 7/tcp echo 7/udp discard 9/tcp sink null discard 9/udp sink null systat 11/tcp users daytime 13/tcp daytime 13/udp netstat 15/tcp qotd 17/tcp quote msp 18/tcp # message send protocol msp 18/udp # message send protocol chargen 19/tcp ttytst source chargen 19/udp ttytst source ftp-data 20/tcp # File Transfer [Default Data] ftp-data 20/udp # File Transfer [Default Data] ftp 21/tcp # File Transfer [Control] ftp 21/udp # File Transfer [Control] ssh 22/tcp # Secure Shell Login ssh 22/udp # Secure Shell Login telnet 23/tcp telnet 23/udp
  • 20. Sockets in Java • Java’s networking facilities are provided in the java.net package – To make a connection to another machine we must first know its IP number—this is done by the InetAddress class • InetAddress goblinsIP = InetAddress.getByName(“goblin”); – Now we can open a socket • Socket mysocket = new Socket(goblinsIP, 23); – This would connect to the telnet port on goblin
  • 21. Sockets in Java • The following methods return input and output streams that you can use to read and write to the socket, just like a file • mysocket.getInputStream(); • Mysocket.getOutputStream(); – Eg: • InputStreamReader in = new InputStreamReader(mysocket.getInputStream()); • OutputStreamWriter out = new OutputStreamWriter(mysocket.getOutputStream());
  • 22. Echoed response Lines of text (strings) java.io.BufferedReader Unicode character stream java.io.InputStreamReader Byte stream from socket java.net.Socket Network
  • 23. Echo Client • There is a program (also known as a service) on most networked machines that echoes back what you write to it. This program connects to that echo service (port 7) and writes and reads to/from it import java.io.*; import java.net.*; public class EchoClient { public static void main(String [] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null;
  • 24. Echo Client... try { InetAddress goblinsIP = InetAddress.getByName(“goblin”); echoSocket = new Socket(goblinsIP, 7); out = new PrintWriter(echoSocket. getOutputStream(), true); in = new BufferedReader(new InputStreamReader(echoSocket. getInputStream());
  • 25. Echo Client } catch (UnknownHostException e) { System.err.println(“Don’t know about “ +”host: goblin.”); System.exit(1); } catch (IOException e) { System.err.println(“Couldn’t get I/O “ +”for connection to: goblin.”); System.exit(1); }
  • 26. Echo Client... BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println(“echo: “ + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } }
  • 27. Echo Client in use. mhall@goblin:~> java EchoClient Boo! echo: Boo! Hello there echo: Hello there Quit echo: Quit
  • 28. Clients and Servers… • So far we have considered a ‘client’ program that connects through a socket to a service (or server) Connect Write Read Close
  • 29. Clients and Servers… • Consider the actions of the server at the other end Listen Accept Read Write Close
  • 30. Clients and Servers… • Java provides the class ServerSocket which listens to connections. Eg: – ServerSocket myserver = new ServerSocket(4420); – This sets up a ServerSocket to listen on port 4420 – Now wait for a connection using the “accept” method. This method returns a reference to a regular socket that can be used to read and write to the connection client – Socket theClient = myserver.accept(); – The socket “theClient” can now be used tp read and write to the connecting client in the usual way
  • 31. Echo Server… import java.io.*; import java.net.*; public class EchoServer { public static void main(String [] args) throws IOException { ServerSocket myserver = null; try { myserver = new ServerSocket(4444); } catch (IOException e) { System.out.println(“Could not listen “ +”on port: 4444.”); System.exit(1); }
  • 32. Echo Server... Socket theclient = null; try { theclient = myserver.accept(); } catch (IOException e) { System.err.pritnln(“Accept failed.”); System.exit(1); } PrintWriter out = new PrintWriter(theclient.getOutputStream(), true)); BufferedReader in = new BufferedReader(new InputStreamReader(theclient. getInputStream()));
  • 33. Echo Server… String inputLine, outputLine; while((inputLine=in.readLine()) != null) { outputLine = inputLine + “ :-)”; out.println(outputLine); if (inputLine.equals(“Bye.”)) { break; } } out.close(); in.close(); theclient.close(); myserver.close(); } }
  • 34. Request for connection ServerSocket Client Program ServerSocket creates socket Socket Socket Port 23 Port X Request for Network connection
  • 35. Server and Client Communicate Server Program Client Program ServerSocket Socket Socket Port 23 Port X Network
  • 36. Multiple Connections… • Consider the case where multiple clients are connected to the same service. Eg. Multiple telnet connections to goblin • How do sockets deal with this?
  • 37. Request for Connection ServerSocket ServerSocket allocates a new socket New Socket Port 23 Request for connection from client
  • 38. Request for Another Connection Server code ServerSocket allocates another ServerSocket socket New Socket Established Socket Port 23 Another request for Client reads and connection writes to server
  • 39. Multiple Connections... •The port records what clients have connected and diverts interaction to the appropriate socket. •A client is identified by: – IP number and Port number! •When a socket is created on the client machine it is allocated a local port number as well. This is the port that the server uses to write to the client