Java/Network Protocol/ServerSocket

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

A multithreaded Socket Server

  
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
  public static void main(String[] args) throws Exception {
    ServerSocket m_ServerSocket = new ServerSocket(12111);
    int id = 0;
    while (true) {
      Socket clientSocket = m_ServerSocket.accept();
      ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
      cliThread.start();
    }
  }
}
class ClientServiceThread extends Thread {
  Socket clientSocket;
  int clientID = -1;
  boolean running = true;
  ClientServiceThread(Socket s, int i) {
    clientSocket = s;
    clientID = i;
  }
  public void run() {
    System.out.println("Accepted Client : ID - " + clientID + " : Address - "
        + clientSocket.getInetAddress().getHostName());
    try {
      BufferedReader   in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      PrintWriter   out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
      while (running) {
        String clientCommand = in.readLine();
        System.out.println("Client Says :" + clientCommand);
        if (clientCommand.equalsIgnoreCase("quit")) {
          running = false;
          System.out.print("Stopping client thread for client : " + clientID);
        } else {
          out.println(clientCommand);
          out.flush();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





A very simple Web server. When it receives a HTTP request it sends the request back as the reply.

  
 
/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
//package je3.net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * This program is a very simple Web server. When it receives a HTTP request it
 * sends the request back as the reply. This can be of interest when you want to
 * see just what a Web client is requesting, or what data is being sent when a
 * form is submitted, for example.
 */
public class HttpMirror {
  public static void main(String args[]) {
    try {
      // Get the port to listen on
      int port = Integer.parseInt(args[0]);
      // Create a ServerSocket to listen on that port.
      ServerSocket ss = new ServerSocket(port);
      // Now enter an infinite loop, waiting for & handling connections.
      for (;;) {
        // Wait for a client to connect. The method will block;
        // when it returns the socket will be connected to the client
        Socket client = ss.accept();
        // Get input and output streams to talk to the client
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintWriter out = new PrintWriter(client.getOutputStream());
        // Start sending our reply, using the HTTP 1.1 protocol
        out.print("HTTP/1.1 200 \r\n"); // Version & status code
        out.print("Content-Type: text/plain\r\n"); // The type of data
        out.print("Connection: close\r\n"); // Will close stream
        out.print("\r\n"); // End of headers
        // Now, read the HTTP request from the client, and send it
        // right back to the client as part of the body of our
        // response. The client doesn"t disconnect, so we never get
        // an EOF. It does sends an empty line at the end of the
        // headers, though. So when we see the empty line, we stop
        // reading. This means we don"t mirror the contents of POST
        // requests, for example. Note that the readLine() method
        // works with Unix, Windows, and Mac line terminators.
        String line;
        while ((line = in.readLine()) != null) {
          if (line.length() == 0)
            break;
          out.print(line + "\r\n");
        }
        // Close socket, breaking the connection to the client, and
        // closing the input and output streams
        out.close(); // Flush and close the output stream
        in.close(); // Close the input stream
        client.close(); // Close the socket itself
      } // Now loop again, waiting for the next connection
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
      System.err.println(e);
      System.err.println("Usage: java HttpMirror <port>");
    }
  }
}





BufferedReader for ServerSocket

  
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HTTPServer {
  public static void main(String[] args) throws Exception {
    ServerSocket sSocket = new ServerSocket(1777);
    while (true) {
      System.out.println("Waiting for a client...");
      Socket newSocket = sSocket.accept();
      System.out.println("accepted the socket");
      OutputStream os = newSocket.getOutputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(newSocket.getInputStream()));
      String inLine = null;
      while (((inLine = br.readLine()) != null) && (!(inLine.equals("")))) {
        System.out.println(inLine);
      }
      System.out.println("");
      StringBuffer sb = new StringBuffer();
      sb.append("<html>\n");
      sb.append("<head>\n");
      sb.append("<title>Java \n");
      sb.append("</title>\n");
      sb.append("</head>\n");
      sb.append("<body>\n");
      sb.append("<H1>HTTPServer Works!</H1>\n");
      sb.append("</body>\n");
      sb.append("</html>\n");
      String string = sb.toString();
      byte[] byteArray = string.getBytes();
      os.write("HTTP/1.0 200 OK\n".getBytes());
      os.write(new String("Content-Length: " + byteArray.length + "\n").getBytes());
      os.write("Content-Type: text/html\n\n".getBytes());
      os.write(byteArray);
      os.flush();
      os.close();
      br.close();
      newSocket.close();
    }
  }
}





Compressed socket

  
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.Socket;
import java.util.zip.GZIPOutputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    Socket sock = new Socket(args[0], Integer.parseInt(args[1]));
    GZIPOutputStream zip = new GZIPOutputStream(sock.getOutputStream());
    String line;
    BufferedReader bis = new BufferedReader(new FileReader(args[2]));
    while (true) {
      line = bis.readLine();
      if (line == null)
        break;
      line = line + "\n";
      zip.write(line.getBytes(), 0, line.length());
    }
    zip.finish();
    zip.close();
    sock.close();
  }
}





Data server

  
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
  public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    while (true) {
      System.out.println("Listening");
      Socket sock = ssock.accept();
      DataOutputStream dstream = new DataOutputStream(sock.getOutputStream());
      dstream.writeFloat(3.14159265f);
      dstream.close();
      sock.close();
    }
  }
}





Get internet address from connected socket client

  
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
  public static void main(String[] args) throws Exception {
    ServerSocket server = new ServerSocket(8123);
    while (true) {
      Socket sock = server.accept();
      InetAddress addr = sock.getInetAddress();
      System.out.println("Connection made to " + addr.getHostName() + " (" + addr.getHostAddress()
          + ")");
      Thread.sleep(5000);
      sock.close();
    }
  }
}





Get IP address from NetworkInterface and create server socket

  
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
public class Main {
  static public void main(String args[]) throws Exception {
    int port = 80;
    NetworkInterface ni = NetworkInterface.getByName("name");
    Enumeration e = ni.getInetAddresses();
    if (!e.hasMoreElements())
      return;
    InetAddress ia = (InetAddress) e.nextElement();
    ServerSocket ss = new ServerSocket(port, 20, ia);
    System.out.println("Listening");
    Socket s = ss.accept();
    System.out.println(s);
  }
}





Manages asynchonous HTTP GET downloads and demonstrates non-blocking I/O with SocketChannel and Selector

  
 
/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
//package je3.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * This class manages asynchonous HTTP GET downloads and demonstrates
 * non-blocking I/O with SocketChannel and Selector and also demonstrates
 * logging with the java.util.logging package. This example uses a number of
 * inner classes and interfaces.
 * 
 * Call download() for each HTTP GET request you want to issue. You may
 * optionally pass a Listener object that will be notified when the download
 * terminates or encounters an exception. download() returns a Download object
 * which holds the downloaded bytes (including HTTP headers) and which allows
 * you to poll the Status of the download. Call release() when there are no more
 * downloads.
 */
public class HttpDownloadManager extends Thread {
  // An enumerated type. Values are returned by Download.getStatus()
  public static class Status {
    // We haven"t connected to the server yet
    public static final Status UNCONNECTED = new Status("Unconnected");
    // We"re connected to the server, sending request or receiving response
    public static final Status CONNECTED = new Status("Connected");
    // Response has been received. Response may have been an HTTP error
    public static final Status DONE = new Status("Done");
    // Something went wrong: bad hostname, for example.
    public static final Status ERROR = new Status("Error");
    private final String name;
    private Status(String name) {
      this.name = name;
    }
    public String toString() {
      return name;
    }
  }
  // Everything you need to know about a pending download
  public interface Download {
    public String getHost(); // Hostname we"re downloading from
    public int getPort(); // Defaults to port 80
    public String getPath(); // includes query string as well
    public Status getStatus(); // Status of the download
    public byte[] getData(); // Download data, including response headers
    public int getHttpStatus();// Only call when status is DONE
  }
  // Implement this interface if you want to know when a download completes
  public interface Listener {
    public void done(Download download);
    public void error(Download download, Throwable throwable);
  }
  Selector selector; // For multiplexing non-blocking I/O.
  ByteBuffer buffer; // A shared buffer for downloads
  List pendingDownloads; // Downloads that don"t have a Channel yet
  boolean released = false; // Set when the release() method is called.
  Logger log; // Logging output goes here
  // The HTTP protocol uses this character encoding
  static final Charset LATIN1 = Charset.forName("ISO-8859-1");
  public HttpDownloadManager(Logger log) throws IOException {
    if (log == null)
      log = Logger.getLogger(this.getClass().getName());
    this.log = log;
    selector = Selector.open(); // create Selector
    buffer = ByteBuffer.allocateDirect(64 * 1024); // allocate buffer
    pendingDownloads = Collections.synchronizedList(new ArrayList());
    this.start(); // start thread
  }
  // Ask the HttpDownloadManager to begin a download. Returns a Download
  // object that can be used to poll the progress of the download. The
  // optional Listener object will be notified of when the download completes
  // or aborts.
  public Download download(URI uri, Listener l) throws IOException {
    if (released)
      throw new IllegalStateException("Can"t download() after release()");
    // Get info from the URI
    String scheme = uri.getScheme();
    if (scheme == null || !scheme.equals("http"))
      throw new IllegalArgumentException("Must use "http:" protocol");
    String hostname = uri.getHost();
    int port = uri.getPort();
    if (port == -1)
      port = 80; // Use default port if none specified
    String path = uri.getRawPath();
    if (path == null || path.length() == 0)
      path = "/";
    String query = uri.getRawQuery();
    if (query != null)
      path += "?" + query;
    // Create a Download object with the pieces of the URL
    Download download = new DownloadImpl(hostname, port, path, l);
    // Add it to the list of pending downloads. This is a synchronized list
    pendingDownloads.add(download);
    // And ask the thread to stop blocking in the select() call so that
    // it will notice and process this new pending Download object.
    selector.wakeup();
    // Return the Download so that the caller can monitor it if desired.
    return download;
  }
  public void release() {
    released = true; // The thread will terminate when it notices the flag.
    try {
      selector.close();
    } // This will wake the thread up
    catch (IOException e) {
      log.log(Level.SEVERE, "Error closing selector", e);
    }
  }
  public void run() {
    log.info("HttpDownloadManager thread starting.");
    // The download thread runs until release() is called
    while (!released) {
      // The thread blocks here waiting for something to happen
      try {
        selector.select();
      } catch (IOException e) {
        // This should never happen.
        log.log(Level.SEVERE, "Error in select()", e);
        return;
      }
      // If release() was called, the thread should exit.
      if (released)
        break;
      // If any new Download objects are pending, deal with them first
      if (!pendingDownloads.isEmpty()) {
        // Although pendingDownloads is a synchronized list, we still
        // need to use a synchronized block to iterate through its
        // elements to prevent a concurrent call to download().
        synchronized (pendingDownloads) {
          Iterator iter = pendingDownloads.iterator();
          while (iter.hasNext()) {
            // Get the pending download object from the list
            DownloadImpl download = (DownloadImpl) iter.next();
            iter.remove(); // And remove it.
            // Now begin an asynchronous connection to the
            // specified host and port. We don"t block while
            // waiting to connect.
            SelectionKey key = null;
            SocketChannel channel = null;
            try {
              // Open an unconnected channel
              channel = SocketChannel.open();
              // Put it in non-blocking mode
              channel.configureBlocking(false);
              // Register it with the selector, specifying that
              // we want to know when it is ready to connect
              // and when it is ready to read.
              key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                  download);
              // Create the web server address
              SocketAddress address = new InetSocketAddress(download.host, download.port);
              // Ask the channel to start connecting
              // Note that we don"t send the HTTP request yet.
              // We"ll do that when the connection completes.
              channel.connect(address);
            } catch (Exception e) {
              handleError(download, channel, key, e);
            }
          }
        }
      }
      // Now get the set of keys that are ready for connecting or reading
      Set keys = selector.selectedKeys();
      if (keys == null)
        continue; // bug workaround; should not be needed
      // Loop through the keys in the set
      for (Iterator i = keys.iterator(); i.hasNext();) {
        SelectionKey key = (SelectionKey) i.next();
        i.remove(); // Remove the key from the set before handling
        // Get the Download object we attached to the key
        DownloadImpl download = (DownloadImpl) key.attachment();
        // Get the channel associated with the key.
        SocketChannel channel = (SocketChannel) key.channel();
        try {
          if (key.isConnectable()) {
            // If the channel is ready to connect, complete the
            // connection and then send the HTTP GET request to it.
            if (channel.finishConnect()) {
              download.status = Status.CONNECTED;
              // This is the HTTP request we wend
              String request = "GET " + download.path + " HTTP/1.1\r\n" + "Host: " + download.host
                  + "\r\n" + "Connection: close\r\n" + "\r\n";
              // Wrap in a CharBuffer and encode to a ByteBuffer
              ByteBuffer requestBytes = LATIN1.encode(CharBuffer.wrap(request));
              // Send the request to the server. If the bytes
              // aren"t all written in one call, we busy loop!
              while (requestBytes.hasRemaining())
                channel.write(requestBytes);
              log
                  .info("Sent HTTP request: " + download.host + ":" + download.port + ": "
                      + request);
            }
          }
          if (key.isReadable()) {
            // If the key indicates that there is data to be read,
            // then read it and store it in the Download object.
            int numbytes = channel.read(buffer);
            // If we read some bytes, store them, otherwise
            // the download is complete and we need to note this
            if (numbytes != -1) {
              buffer.flip(); // Prepare to drain the buffer
              download.addData(buffer); // Store the data
              buffer.clear(); // Prepare for another read
              log.info("Read " + numbytes + " bytes from " + download.host + ":" + download.port);
            } else {
              // If there are no more bytes to read
              key.cancel(); // We"re done with the key
              channel.close(); // And with the channel.
              download.status = Status.DONE;
              if (download.listener != null) // notify listener
                download.listener.done(download);
              log.info("Download complete from " + download.host + ":" + download.port);
            }
          }
        } catch (Exception e) {
          handleError(download, channel, key, e);
        }
      }
    }
    log.info("HttpDownloadManager thread exiting.");
  }
  // Error handling code used by the run() method:
  // set status, close channel, cancel key, log error, notify listener.
  void handleError(DownloadImpl download, SocketChannel channel, SelectionKey key,
      Throwable throwable) {
    download.status = Status.ERROR;
    try {
      if (channel != null)
        channel.close();
    } catch (IOException e) {
    }
    if (key != null)
      key.cancel();
    log.log(Level.WARNING, "Error connecting to or downloading from " + download.host + ":"
        + download.port, throwable);
    if (download.listener != null)
      download.listener.error(download, throwable);
  }
  // This is the Download implementation we use internally.
  static class DownloadImpl implements Download {
    final String host; // Final fields are immutable for thread-saftey
    final int port;
    final String path;
    final Listener listener;
    volatile Status status; // Volatile fields may be changed concurrently
    volatile byte[] data = new byte[0];
    DownloadImpl(String host, int port, String path, Listener listener) {
      this.host = host;
      this.port = port;
      this.path = path;
      this.listener = listener;
      this.status = Status.UNCONNECTED; // Set initial status
    }
    // These are the basic getter methods
    public String getHost() {
      return host;
    }
    public int getPort() {
      return port;
    }
    public String getPath() {
      return path;
    }
    public Status getStatus() {
      return status;
    }
    public byte[] getData() {
      return data;
    }
    /**
     * Return the HTTP status code for the download. Throws
     * IllegalStateException if status is not Status.DONE
     */
    public int getHttpStatus() {
      if (status != Status.DONE)
        throw new IllegalStateException();
      // In HTTP 1.1, the return code is in ASCII bytes 10-12.
      return (data[9] - "0") * 100 + (data[10] - "0") * 10 + (data[11] - "0") * 1;
    }
    // Used internally when we read more data.
    // This should use a larger buffer to prevent frequent re-allocation.
    void addData(ByteBuffer buffer) {
      assert status == Status.CONNECTED; // only called during download
      int oldlen = data.length; // How many existing bytes
      int numbytes = buffer.remaining(); // How many new bytes
      int newlen = oldlen + numbytes;
      byte[] newdata = new byte[newlen]; // Create new array
      System.arraycopy(data, 0, newdata, 0, oldlen); // Copy old bytes
      buffer.get(newdata, oldlen, numbytes); // Copy new bytes
      data = newdata; // Save new array
    }
  }
  // This class demonstrates a simple use of HttpDownloadManager.
  public static class Test {
    static int completedDownloads = 0;
    public static void main(String args[]) throws IOException, URISyntaxException {
      // With a -v argument, our logger will display lots of messages
      final boolean verbose = args[0].equals("-v");
      int firstarg = 0;
      Logger logger = Logger.getLogger(Test.class.getName());
      if (verbose) {
        firstarg = 1;
        logger.setLevel(Level.INFO);
      } else
        // regular output
        logger.setLevel(Level.WARNING);
      // How many URLs are on the command line?
      final int numDownloads = args.length - firstarg;
      // Create the download manager
      final HttpDownloadManager dm = new HttpDownloadManager(logger);
      // Now loop through URLs and call download() for each one
      // passing a listener object to receive notifications
      for (int i = firstarg; i < args.length; i++) {
        URI uri = new URI(args[i]);
        dm.download(uri, new Listener() {
          public void done(Download d) {
            System.err.println("DONE: " + d.getHost() + ": " + d.getHttpStatus());
            // If all downloads are complete, we"re done
            // with the HttpDownloadManager thread.
            if (++completedDownloads == numDownloads)
              dm.release();
          }
          public void error(Download d, Throwable t) {
            System.err.println(d.getHost() + ": " + t);
            if (++completedDownloads == numDownloads)
              dm.release();
          }
        });
      }
    }
  }
}





Object server

  
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
public class Main {
  public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    Hashtable hash = new Hashtable();
    hash.put("A", "a");
    while (true) {
      Socket sock = ssock.accept();
      ObjectOutputStream ostream = new ObjectOutputStream(sock.getOutputStream());
      ostream.writeObject(hash);
      ostream.close();
      sock.close();
    }
  }
}





Print stream server

  
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
  public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    Socket sock = ssock.accept();
    ssock.close();
    PrintStream pstream = new PrintStream(sock.getOutputStream());
    for (int i = 100; i >= 0; i--) {
      pstream.println(i);
    }
    pstream.close();
    sock.close();
  }
}





Read and write with ServerSocket

  
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class SquareServer {
  private final static int BUFSIZE = 20;
  public static void main(String args[]) throws Exception {
    int port = Integer.parseInt(args[0]);
    ServerSocket ss = new ServerSocket(port);
    while (true) {
      Socket s = ss.accept();
      InputStream is = s.getInputStream();
      DataInputStream dis = new DataInputStream(is);
      double value = dis.readDouble();
      value *= value;
      OutputStream os = s.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeDouble(value);
      s.close();
    }
  }
}





ServerSocket per Socket

  
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class LoopingSocketServer {
  public static void main(String args[]) throws Exception {
    ServerSocket servSocket;
    Socket fromClientSocket;
    int cTosPortNumber = 1777;
    String str;
    servSocket = new ServerSocket(cTosPortNumber);
    System.out.println("Waiting for a connection on " + cTosPortNumber);
    fromClientSocket = servSocket.accept();
    System.out.println("fromClientSocket accepted");
    ObjectOutputStream oos = new ObjectOutputStream(fromClientSocket.getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(fromClientSocket.getInputStream());
    while ((str = (String) ois.readObject()) != null) {
      System.out.println("The message from client:  " + str);
      if (str.equals("bye")) {
        oos.writeObject("bye bye");
        break;
      } else {
        str = "Server returns " + str;
        oos.writeObject(str);
      }
    }
    oos.close();
    fromClientSocket.close();
  }
}





Start new thread for each client

  
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
  public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    while (true) {
      Socket sock = ssock.accept();
      new SocketThread(sock).start();
    }
  }
}
class SocketThread extends Thread {
  Socket csocket;
  public SocketThread(Socket csocket) {
    this.csocket = csocket;
  }
  public void run() {
    try {
      PrintStream pstream = new PrintStream(csocket.getOutputStream());
      for (int i = 10; i >= 0; i--) {
        pstream.println(i);
      }
      pstream.close();
      csocket.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}





String value based server

  
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
  public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    Socket sock = ssock.accept();
    ssock.close();
    PrintStream pstream = new PrintStream(sock.getOutputStream());
    pstream.print("count? ");
    BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    String line = input.readLine();
    pstream.println("");
    int count = Integer.parseInt(line);
    for (int i = count; i >= 0; i--) {
      pstream.println(i);
    }
    pstream.close();
    sock.close();
  }
}





Threaded Server with ServerSocket

  
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class ThreadedServer {
  private final static int BUFSIZE = 512;
  public static void main(String args[]) throws Exception {
    int port = Integer.parseInt(args[0]);
    ServerSocket ss = new ServerSocket(port);
    while (true) {
      Socket s = ss.accept();
      ServerThread st = new ServerThread(s);
      st.start();
    }
  }
}
class ServerThread extends Thread {
  private double total = 0;
  DataInputStream dis;
  DataOutputStream dos;
  public ServerThread(Socket s) throws Exception {
    InputStream is = s.getInputStream();
    dis = new DataInputStream(is);
    OutputStream os = s.getOutputStream();
    dos = new DataOutputStream(os);
  }
  public void run() {
    try {
      while (true) {
        double value = dis.readDouble();
        total += value;
        dos.writeDouble(total);
      }
    } catch (Exception e) {
    }
  }
}





Write number to client

  
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class ServerSocketDemo {
  public static void main(String args[]) throws Exception {
    int port = Integer.parseInt(args[0]);
    ServerSocket ss = new ServerSocket(port);
    while (true) {
      Socket s = ss.accept();
      OutputStream os = s.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeInt(1);
      s.close();
    }
  }
}





Zip server socket

 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.net.Socket;
 
class ZipSocket extends Socket {
    private InputStream in;
    private OutputStream out;
    public ZipSocket() { super(); }
    public ZipSocket(String host, int port) 
        throws IOException {
        super(host, port);
    }
    public InputStream getInputStream() 
        throws IOException {
        if (in == null) {
            in = new ZipInputStream(super.getInputStream());
        }
        return in;
    }
    public OutputStream getOutputStream() 
        throws IOException {
        if (out == null) {
            out = new ZipOutputStream(super.getOutputStream());
        }
        return out;
    }
   
    public synchronized void close() throws IOException {
        OutputStream o = getOutputStream();
        o.flush();
  super.close();
    }
}

import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class ZipServerSocket extends ServerSocket
{
  public ZipServerSocket(int port) throws IOException
  { 
  super(port);
  }
  public Socket accept() throws IOException
  { 
     Socket socket = new ZipSocket();
     implAccept(socket);
     return socket;
  }
}