Java Tutorial/Network/Socket Client

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Create a socket with a timeout

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
public class Main {
  public static void main(String[] argv) throws Exception {
    InetAddress addr = InetAddress.getByName("java.sun.ru");
    int port = 80;
    SocketAddress sockaddr = new InetSocketAddress(addr, port);
    Socket sock = new Socket();
    int timeoutMs = 2000; // 2 seconds
    sock.connect(sockaddr, timeoutMs);
  }
}





Create a socket without a timeout

import java.net.InetAddress;
import java.net.Socket;
public class Main {
  public static void main(String[] argv) throws Exception {
    InetAddress addr = InetAddress.getByName("java.sun.ru");
    int port = 80;
    Socket socket = new Socket(addr, port);
  }
}





Daytime Client

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainClass {
  public static void main(String[] args) {
    String hostname = "time.nist.gov";
    try {
      Socket theSocket = new Socket(hostname, 13);
      InputStream timeStream = theSocket.getInputStream();
      StringBuffer time = new StringBuffer();
      int c;
      while ((c = timeStream.read()) != -1)
        time.append((char) c);
      String timeString = time.toString().trim();
      System.out.println("It is " + timeString + " at " + hostname);
    } // end try
    catch (UnknownHostException ex) {
      System.err.println(ex);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}





Day time Client (Getting the time)

import java.io.InputStream;
import java.net.Socket;
public class MainClass {
  public static void main(String[] args)throws Exception {
    String hostname = "tock.usno.navy.mil";
    Socket theSocket = new Socket(hostname, 13);
    InputStream timeStream = theSocket.getInputStream();
    StringBuffer time = new StringBuffer();
    int c;
    while ((c = timeStream.read()) != -1)
      time.append((char) c);
    String timeString = time.toString().trim();
    System.out.println("It is " + timeString + " at " + hostname);
  }
}





Echo Client

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class MainClass {
  public static void main(String[] args) throws Exception {
    String hostname = "localhost";
    Socket theSocket = new Socket(hostname, 7);
    BufferedReader networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
    BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out = new PrintWriter(theSocket.getOutputStream());
    System.out.println("Connected to echo server");
    while (true) {
      String theLine = userIn.readLine();
      if (theLine.equals("."))
        break;
      out.println(theLine);
      out.flush();
      System.out.println(networkIn.readLine());
    }
    networkIn.close();
    out.close();
  }
}





Finger Client

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
public class MainClass {
  public final static int DEFAULT_PORT = 79;
  public static void main(String[] args) throws Exception {
    String hostname = "localhost";
    Socket connection = null;
    connection = new Socket(hostname, DEFAULT_PORT);
    Writer out = new OutputStreamWriter(connection.getOutputStream(), "8859_1");
    out.write("\r\n");
    out.flush();
    InputStream raw = connection.getInputStream();
    BufferedInputStream buffer = new BufferedInputStream(raw);
    InputStreamReader in = new InputStreamReader(buffer, "8859_1");
    int c;
    while ((c = in.read()) != -1) {
      if ((c >= 32 && c < 127) || c == "\t" || c == "\r" || c == "\n") {
        System.out.write(c);
      }
    }
    connection.close();
  }
}





Read and write through socket

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Main {
  public static void whois(String query, String server) throws IOException {
    Socket sock = new Socket(server, 43);
    int c = 0;
    
    OutputStream os = sock.getOutputStream();
    InputStream is = sock.getInputStream();
    query += "\r\n";
    os.write(query.getBytes("iso8859_1"));
    while (c != -1) {
      c = is.read();
      if (c != -1)
        System.out.println((char) c);
    }
  }
  public static void main(String[] args) throws Exception {
    String hostname = "whois.networksolutions.ru";
    whois("query", hostname);
  }
}





Send string to each connected client

import java.net.ServerSocket;
import java.net.Socket;
class MTServerBase extends Thread {
  Socket socket;
  public void run() {
    try {
      String s = "I"m a server.";
      socket.getOutputStream().write(s.getBytes());
      socket.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  static public void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(8080);
    while (true) {
      Socket esock = null;
      esock = ssock.accept();
      MTServerBase t = new MTServerBase();
      t.socket = esock;
      t.start();
      esock.close();
    }
  }
}





Time Client

import java.io.InputStream;
import java.net.Socket;
import java.util.Date;
public class MainClass {
  public static void main(String[] args) throws Exception {
    String hostname = "time.nist.gov";
    int port = 37;
    InputStream raw = null;
    Socket theSocket = new Socket(hostname, port);
    raw = theSocket.getInputStream();
    System.out.println(raw.read());
    raw.close();
  }
}





Whois Client

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.Socket;
public class MainClass {
  public final static int DEFAULT_PORT = 43;
  public final static String DEFAULT_HOST = "whois.internic.net";
  public static void main(String[] args) throws Exception {
    String serverName = System.getProperty("WHOIS_SERVER", DEFAULT_HOST);
    InetAddress server = null;
    server = InetAddress.getByName(serverName);
    Socket theSocket = new Socket(server, DEFAULT_PORT);
    Writer out = new OutputStreamWriter(theSocket.getOutputStream(), "8859_1");
    out.write("\r\n");
    out.flush();
    InputStream raw = theSocket.getInputStream();
    InputStream in = new BufferedInputStream(theSocket.getInputStream());
    int c;
    while ((c = in.read()) != -1)
      System.out.write(c);
  }
}





Zip 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();
    }
}