Java/Network Protocol/Various Clients

Материал из Java эксперт
Перейти к: навигация, поиск

Multicast Client

/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MulticastClient {
  public static void main(String[] args) throws IOException {
    MulticastSocket socket = new MulticastSocket(4446);
    InetAddress address = InetAddress.getByName("230.0.0.1");
    socket.joinGroup(address);
    DatagramPacket packet;
    // get a few quotes
    for (int i = 0; i < 5; i++) {
      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);
      String received = new String(packet.getData());
      System.out.println("Quote of the Moment: " + received);
    }
    socket.leaveGroup(address);
    socket.close();
  }
}
/////////////////////////////////////////////////
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
public class MulticastServer {
  public static void main(String[] args) throws java.io.IOException {
    new MulticastServerThread().start();
  }
}
class MulticastServerThread extends QuoteServerThread {
  private long FIVE_SECONDS = 5000;
  public MulticastServerThread() throws IOException {
    super("MulticastServerThread");
  }
  public void run() {
    while (moreQuotes) {
      try {
        byte[] buf = new byte[256];
        // construct quote
        String dString = null;
        if (in == null)
          dString = new Date().toString();
        else
          dString = getNextQuote();
        buf = dString.getBytes();
        // send it
        InetAddress group = InetAddress.getByName("230.0.0.1");
        DatagramPacket packet = new DatagramPacket(buf, buf.length,
            group, 4446);
        socket.send(packet);
        // sleep for a while
        try {
          sleep((long) (Math.random() * FIVE_SECONDS));
        } catch (InterruptedException e) {
        }
      } catch (IOException e) {
        e.printStackTrace();
        moreQuotes = false;
      }
    }
    socket.close();
  }
}
class QuoteServerThread extends Thread {
  protected DatagramSocket socket = null;
  protected BufferedReader in = null;
  protected boolean moreQuotes = true;
  public QuoteServerThread() throws IOException {
    this("QuoteServerThread");
  }
  public QuoteServerThread(String name) throws IOException {
    super(name);
    socket = new DatagramSocket(4445);
    try {
      in = new BufferedReader(new FileReader("one-liners.txt"));
    } catch (FileNotFoundException e) {
      System.err
          .println("Could not open quote file. Serving time instead.");
    }
  }
  public void run() {
    while (moreQuotes) {
      try {
        byte[] buf = new byte[256];
        // receive request
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);
        // figure out response
        String dString = null;
        if (in == null)
          dString = new Date().toString();
        else
          dString = getNextQuote();
        buf = dString.getBytes();
        // send the response to the client at "address" and "port"
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        packet = new DatagramPacket(buf, buf.length, address, port);
        socket.send(packet);
      } catch (IOException e) {
        e.printStackTrace();
        moreQuotes = false;
      }
    }
    socket.close();
  }
  protected String getNextQuote() {
    String returnValue = null;
    try {
      if ((returnValue = in.readLine()) == null) {
        in.close();
        moreQuotes = false;
        returnValue = "No more quotes. Goodbye.";
      }
    } catch (IOException e) {
      returnValue = "IOException occurred in server.";
    }
    return returnValue;
  }
}
//file: one-liners.txt

/*
Life is wonderful. Without it we"d all be dead.
Daddy, why doesn"t this magnet pick up this floppy disk?
Give me ambiguity or give me something else.
I.R.S.: We"ve got what it takes to take what you"ve got!
We are born naked, wet and hungry. Then things get worse.
Make it idiot proof and someone will make a better idiot.
He who laughs last thinks slowest!
Always remember you"re unique, just like everyone else.
"More hay, Trigger?" "No thanks, Roy, I"m stuffed!"
A flashlight is a case for holding dead batteries.
Lottery: A tax on people who are bad at math.
Error, no keyboard - press F1 to continue.
There"s too much blood in my caffeine system.
Artificial Intelligence usually beats real stupidity.
Hard work has a future payoff. Laziness pays off now.
"Very funny, Scotty. Now beam down my clothes."
Puritanism: The haunting fear that someone, somewhere may be happy.
Consciousness: that annoying time between naps.
Don"t take life too seriously, you won"t get out alive.
I don"t suffer from insanity. I enjoy every minute of it.
Better to understand a little than to misunderstand a lot.
The gene pool could use a little chlorine.
When there"s a will, I want to be in it.
Okay, who put a "stop payment" on my reality check?
We have enough youth, how about a fountain of SMART?
Programming is an art form that fights back.
"Daddy, what does FORMATTING DRIVE C mean?"
All wiyht. Rho sritched mg kegtops awound?
My mail reader can beat up your mail reader.
Never forget: 2 + 2 = 5 for extremely large values of 2.
Nobody has ever, ever, EVER learned all of WordPerfect.
To define recursion, we must first define recursion.
Good programming is 99% sweat and 1% coffee.
Home is where you hang your @
The E-mail of the species is more deadly than the mail.
A journey of a thousand sites begins with a single click.
You can"t teach a new mouse old clicks.
Great groups from little icons grow.
Speak softly and carry a cellular phone.
C:\ is the root of all directories.
Don"t put all your hypes in one home page.
Pentium wise; pen and paper foolish.
The modem is the message.
Too many clicks spoil the browse.
The geek shall inherit the earth.
A chat has nine lives.
Don"t byte off more than you can view.
Fax is stranger than fiction.
What boots up must come down.
Windows will never cease.   (ed. oh sure...)
In Gates we trust.    (ed.  yeah right....)
Virtual reality is its own reward.
Modulation in all things.
A user and his leisure time are soon parted.
There"s no place like http://www.home.ru
Know what to expect before you connect.
Oh, what a tangled website we weave when first we practice.
Speed thrills.
Give a man a fish and you feed him for a day; teach him to use the Net and he won"t bother you for weeks.

*/





This finger client allows you to query a remote host.

/*       
Chapter 3 - Simple Protocols
Java 2 Network Protocols Black Book
by Al Williams    
Paraglyph Press 2001
*/
import java.net.*;
import java.io.*;
public class Finger {
    public String finger(String host, String users) 
       throws IOException, SocketException {
       String outstring="";
       int c=0;
       Socket sock=new Socket(host,79);
       OutputStream os = sock.getOutputStream();
       InputStream is = sock.getInputStream();
       users = users + "\r\n";
       os.write(users.getBytes("iso8859_1"));
       try {
           while (c!=-1) {
             c=is.read();
             if (c!=-1) outstring+=(char)c;
           }
       }
       catch (IOException e) {}
       return outstring;
    }
    public static void main(String[] args) {
    
       String hostname = "";
       String ulist = "";
       if (args.length==0) {
           System.out.println("usage: finger host [user]");
           System.exit(1);
       }
       if (args.length>=2) 
           for (int i=1; i<args.length; i++) 
             ulist+=args[i]+" ";
       hostname=args[0];
       Finger worker = new Finger();
       try {
         System.out.println(worker.finger(hostname,ulist.trim()));
       }
       catch (Exception e) {
           System.out.println(e);
       }
    }
}





This whois client defaults to the whois.internic.net server

/*
Chapter 3 - Simple Protocols
Java 2 Network Protocols Black Book
by Al Williams    
Paraglyph Press 2001
*/
import java.net.*;
import java.io.*;
public class Whois {
    public void whois(String query) throws IOException {
    whois(query,"whois.internic.net");
    }
    public String whois(String query, String server) throws IOException {
       Socket sock = new Socket(server,43);
       int c=0;
       String outstring="";
       OutputStream os = sock.getOutputStream();
       InputStream is = sock.getInputStream();
       query += "\r\n";
       os.write(query.getBytes("iso8859_1"));
       try {
           while (c!=-1) {
             c=is.read();
             if (c!=-1) outstring+=(char)c;
           }
       }
       catch (IOException e) {}
       return outstring;
    }
    public static void main(String[] args) {
       String hostname = "";
       String ulist = "";
       if (args.length==0) {
           System.out.println("usage: whois [%host] query");
           System.exit(1);
       }
       int argn=0;
       hostname="whois.networksolutions.ru"; // default
       if (args.length>1 && args[0].charAt(0)=="%") {
           hostname=args[argn].substring(1);
            argn++;
       }
        for (int i=argn; i<args.length; i++) 
             ulist+=args[i]+" ";
       Whois worker = new Whois();
       try {
           System.out.println(worker.whois(ulist.trim(),hostname));
       }
       catch (Exception e) {
           System.out.println(e);
       }
    }
}





Use Socket to read from whois.internic.net

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
public class whois {
  public final static int port = 43;
  public final static String hostname = "whois.internic.net";
  public static void main(String[] args) {
    Socket theSocket;
    DataInputStream theWhoisStream;
    PrintStream ps;
    try {
      theSocket = new Socket(hostname, port, true);
      ps = new PrintStream(theSocket.getOutputStream());
      for (int i = 0; i < args.length; i++) ps.print(args[i] + " ");
      ps.print("\r\n");
      theWhoisStream = new DataInputStream(theSocket.getInputStream());
      String s;
      while ((s = theWhoisStream.readLine()) != null) {
        System.out.println(s);
      }
    }
    catch (IOException e) {
      System.err.println(e);
    }
  }
}