03-10-11-java-netprog (1)

download 03-10-11-java-netprog (1)

of 17

Transcript of 03-10-11-java-netprog (1)

  • 8/7/2019 03-10-11-java-netprog (1)

    1/17

  • 8/7/2019 03-10-11-java-netprog (1)

    2/17

  • 8/7/2019 03-10-11-java-netprog (1)

    3/17

  • 8/7/2019 03-10-11-java-netprog (1)

    4/17

  • 8/7/2019 03-10-11-java-netprog (1)

    5/17

    9 Java Network Programming

    import java.io.*;

    import java.net.*;

    public class SendBytesTCP02 {

    public static void main(String args[]) {

    if(args.length != 2 ) {System.err.println("need host name or IP and port");

    System.exit(1);

    }

    String host = args[0];

    int port = Integer.parseInt(args[1]);

    try {

    Socket conn=new Socket(host, port);

    OutputStream outs=conn.getOutputStream();

    byte buf[] = new byte[1024];

    while (true) {

    int rc = System.in.read(buf,0,1024);

    if(rc

  • 8/7/2019 03-10-11-java-netprog (1)

    6/17

    11 Java Network Programming

    Example Page

    This is the first paragraph, it is terminated by a

    ...

    which will get tiny.html from tink.stca.herts.ac.uk. Notes: first attempt to connect to the server by creating a new socket using the remote system

    name (or number) and the port:

    socket = new Socket(args[0], port);

    if this fails an exception will be raised but not caught so the program will fail,

    now extract the input and output streams:

    toServer = socket.getOutputStream();fromServer = socket.getInputStream();

    now build a full HTTP file request as a string in request, although read and write

    work with byte arrays it is easier to build a request using a Java String,

    and send it to the server:

    toServer.write(request.getBytes());

    but the String request must now be changed to bytes because write requires anarray of bytes, getBytes will get such an array out of the String request. Now the

    message is sent to the server,

    if the server exists and if it reads the request, and if it thinks our request well-formed

    and if it has such a file then it will send it down the same connected socket. We must

    read the socket to get the returning file:

    rc = fromServer.read(buffer,0,8192);

    read puts the characters read into a pre-allocated array of bytes, here called buffer.

    The return result, put in rc, is the number of characters actually put in buffer. The

    client cannot know how big the file is (if its an MPEG video it might be megabytes),

    so it reads in chunks of 8k, that is why there is a loop, that reads and then prints to

    System.out,

    when we can read no more (rc

  • 8/7/2019 03-10-11-java-netprog (1)

    7/17

  • 8/7/2019 03-10-11-java-netprog (1)

    8/17

  • 8/7/2019 03-10-11-java-netprog (1)

    9/17

  • 8/7/2019 03-10-11-java-netprog (1)

    10/17

    19 Java Network Programming

    12 public static void main(String[] args) throws Exception {

    13 System.setProperty( "java.net.preferIPv4Stack", "true" );

    14 int port = 80;

    15 byte buffer[] = new byte[2048];

    16

    17 Socket socket = new Socket(args[0], port);18 OutputStream toServer = socket.getOutputStream();

    19 InputStream fromServer = socket.getInputStream();

    20 String request =

    21 "GET " + args[1] + " HTTP/1.1\r\n"

    22 + "Host: " + args[0] + "\r\n"

    23 + "Connection: Close\r\n\r\n";

    24

    25 toServer.write(request.getBytes());

    26

    27 // now read server response and skip option lines28 // followed by file

    29 String firstLine = readLine(fromServer);

    30 while(true) {

    31 String line = readLine(fromServer);

    32 if(line.length() == 0) break;

    33 }

    34 // all header lines read, check first to see if OK

    35 if(! (firstLine.startsWith("HTTP") && firstLine.contains("200")) ) {

    36 // not 200 OK response

    37 System.err.println("Not 200 OK");

    38 } else { // OK save the file

    39 String fname=args[1].substring(1);

    40 OutputStream ofile = new FileOutputStream(fname);

    41

    42 while (true) {

    43 int rc = fromServer.read(buffer,0,2048);

    44 if(rc

  • 8/7/2019 03-10-11-java-netprog (1)

    11/17

  • 8/7/2019 03-10-11-java-netprog (1)

    12/17

  • 8/7/2019 03-10-11-java-netprog (1)

    13/17

  • 8/7/2019 03-10-11-java-netprog (1)

    14/17

    27 Java Network Programming

    it doesnt do much but it does allow the program to compile. Here is some output fromthis version:

    ababababababababababababababababababababababababababab

    ababababababababababababababababababababababababababab

    ababababababababababababababababababababababababababab

    ababababababababababababababababababababababababababab

    6.3 A concurrent echo server

    If a server has to deal with a long transaction for a client, involving lots of waits forreading and writing files and sockets, it will be unable to accept new requests. Onesimple solution is to change the server so that after the accept it creates a child thread.This new thread uses the new connected socket to service the clients request, and thendies. The parent thread goes back to accept to await another connection. This is called a

    concurrent server.

    import java.io.*;

    import java.net.*;

    class ServiceThread extends Thread {

    Socket conn=null;

    public ServiceThread(Socket c) { conn = c; }

    public void run() {final int bufsiz=16384;

    byte buff[] = new byte[bufsiz];

    try {

    OutputStream out = conn.getOutputStream();

    InputStream in = conn.getInputStream();

    while (true) {

    int rc = in.read(buff,0,bufsiz);

    if(rc

  • 8/7/2019 03-10-11-java-netprog (1)

    15/17

  • 8/7/2019 03-10-11-java-netprog (1)

    16/17

    k i

  • 8/7/2019 03-10-11-java-netprog (1)

    17/17

    33 Java Network Programming

    Note:

    it takes its port as a command line argument, and uses it to create a new listening

    DatagramSocket,

    it creates a DatagramPacket with a byte array of length 1024, there is no receiver

    address so this is to store received packets,

    it then enters a loop and waits for a datagram by calling receive on the socket:

    socket.receive(packet);

    the packet to put the datagram into is the argument.

    when a packet arrives this program can extract information from the Datagram, the

    sender address, the senders (ephemeralmore later) port number, and the data.

    Here is a sender program:

    import java.io.*;

    import java.net.*;

    public class SendUDP0 {

    public static void main(String[] args)

    throws Exception {

    DatagramSocket socket = new DatagramSocket();

    DatagramPacket packet;

    InetAddress iaddr = InetAddress.getByName(args[0]);

    int port = Integer.parseInt(args[1]);

    BufferedReader stdIn =

    new BufferedReader(new InputStreamReader(System.in));

    String userInput;

    userInput = stdIn.readLine();

    while (userInput != null) {

    packet = new DatagramPacket(userInput.getBytes(),

    userInput.length(),iaddr,port);socket.send(packet);

    userInput = stdIn.readLine();

    }

    stdIn.close();

    socket.close();

    }

    }

    Note:

    it takes a destination address and port as a command line arguments, it will use these

    to send the datagram,

    34

    it creates a DatagramSocket with port, it is the sender,

    it enters a loop, each time reading a line from the keyboard, if end of file is typed (d)

    it gets null and stops, otherwise it sends the input to the receiver program and repeats

    the loop,

    it creates a new DatagramPacket. The first argument is the message obtained byconverting the String to a byte array using .getBytes(). It also has to provide the

    destination InetAddress and port number,

    it then sends the datagram using socket.send(...).