Java Tutorial/Network/Socket

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

A Thin SMTP Client

   <source lang="java">

import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Main {

 public static void main(String[] args) throws Exception {
   String host = "host";
   int port = 25;
   String from = "from@from.net";
   String toAddr = "to@to.net";
   Socket servSocket = new Socket(host, port);
   DataOutputStream os = new DataOutputStream(servSocket.getOutputStream());
   DataInputStream is = new DataInputStream(servSocket.getInputStream());
   if (servSocket != null && os != null && is != null) {
     os.writeBytes("HELO\r\n");
     os.writeBytes("MAIL From:" + from + " \r\n");
     os.writeBytes("RCPT To:" + toAddr + "\r\n");
     os.writeBytes("DATA\r\n");
     os.writeBytes("X-Mailer: Java\r\n");
     os.writeBytes("DATE: " + DateFormat.getDateInstance(DateFormat.FULL, Locale.US).format(new Date()) + "\r\n");
     os.writeBytes("From:" + from + "\r\n");
     os.writeBytes("To:" + toAddr + "\r\n");
   }
   os.writeBytes("Subject:\r\n");
   os.writeBytes("body\r\n");
   os.writeBytes("\r\n.\r\n");
   os.writeBytes("QUIT\r\n");
   String responseline;
   while ((responseline = is.readUTF()) != null) { 
     if (responseline.indexOf("Ok") != -1)
       break;
   }
 }

}</source>





Cipher Socket

   <source lang="java">

/*

* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.SecretKey; /**

*
* @author  Scott.Stark@jboss.org
*/

public class CipherSocket extends Socket {

  private Cipher cipher;
  private Socket delegate;
  String algorithm;
  SecretKey key;
  /** Creates a new instance of CipherSocket */
  public CipherSocket(String host, int port, String algorithm, SecretKey key)
     throws IOException
  {
     super(host, port);
     this.algorithm = algorithm;
     this.key = key;
  }
  public CipherSocket(Socket delegate, String algorithm, SecretKey key)
     throws IOException
  {
     this.delegate = delegate;
     this.algorithm = algorithm;
     this.key = key;
  }
  public InputStream getInputStream() throws IOException
  {
     InputStream is = delegate == null ? super.getInputStream() : delegate.getInputStream();
     Cipher cipher = null;
     try
     {
        cipher = Cipher.getInstance(algorithm);
        int size = cipher.getBlockSize();
        byte[] tmp = new byte[size];
        Arrays.fill(tmp, (byte)15);
        IvParameterSpec iv = new IvParameterSpec(tmp);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
     }
     catch(Exception e)
     {
        e.printStackTrace();
        throw new IOException("Failed to init cipher: "+e.getMessage());
     }
     CipherInputStream cis = new CipherInputStream(is, cipher);
     return cis;
  }
  public OutputStream getOutputStream() throws IOException
  {
     OutputStream os = delegate == null ? super.getOutputStream() : delegate.getOutputStream();
     Cipher cipher = null;
     try
     {
        cipher = Cipher.getInstance(algorithm);
        int size = cipher.getBlockSize();
        byte[] tmp = new byte[size];
        Arrays.fill(tmp, (byte)15);
        IvParameterSpec iv = new IvParameterSpec(tmp);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
     }
     catch(Exception e)
     {
        throw new IOException("Failed to init cipher: "+e.getMessage());
     }
     CipherOutputStream cos = new CipherOutputStream(os, cipher);
     return cos;
  }

}</source>





Create a socket

   <source lang="java">

import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class MainClass {

 public static void main(String args[]) {
   try {
     Socket socket = new Socket("192.2.1.168", 23);
   } catch (UnknownHostException e) {
     System.out.println(e);
   } catch (IOException e2) {
     System.out.println(e2);
   }
 }

}</source>





Create Socket by IP address and port number

   <source lang="java">

import java.net.Socket; public class MainClass {

 public static void main(String[] args) throws Exception {
   Socket s = new Socket("127.0.0.1", 0);
   System.out.println(s.getPort());
 }

}</source>





Display Socket InetAddress, Port, LocalPort and Local address

   <source lang="java">

import java.net.Socket; public class MainClass {

 public static void main(String[] args) throws Exception {
   Socket theSocket = new Socket("127.0.0.1", 80);
   System.out.println("Connected to " + theSocket.getInetAddress() + " on port "
       + theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of "
       + theSocket.getLocalAddress());
 }

}</source>





Get InputStream and OutputStream from Socket

   <source lang="java">

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class MainClass {

 public static void main(String[] args) {
   try {
     Socket s = new Socket("127.0.0.1", 80);
     OutputStream out = s.getOutputStream();
     out.close();
     InputStream in = s.getInputStream();
   } catch (IOException e) {
     System.err.println(e);
   }
 }

}</source>





Get internet address from connected socket client

   <source lang="java">

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

}</source>





java.net.Socket

  1. A socket is an endpoint of a network connection.
  2. A socket enables an application to read from and write to the network.
  3. The Socket class represents a "client" socket.

A simple HTTP client



   <source lang="java">

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class MainClass {

 public static void main(String[] args) {
   String host = "www.google.ru";
   String protocol = "http";
   try {
     Socket socket = new Socket(protocol + "://" + host, 80);
     OutputStream os = socket.getOutputStream();
     boolean autoflush = true;
     PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
     BufferedReader in = new BufferedReader(
     new InputStreamReader(socket.getInputStream()));
     // send an HTTP request to the web server
     out.println("GET / HTTP/1.1");
     out.println("Host: " + host + ":80");
     out.println("Connection: Close");
     out.println();
     // read the response
     boolean loop = true;
     StringBuilder sb = new StringBuilder(8096);
     while (loop) {
       if (in.ready()) {
         int i = 0;
         while (i != -1) {
           i = in.read();
           sb.append((char) i);
         }
         loop = false;
       }
     }
     // display the response to the out console
     System.out.println(sb.toString());
     socket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }

}</source>





Read float number from a Socket

   <source lang="java">

import java.io.DataInputStream; import java.net.Socket; public class Main {

 public static void main(String[] args) throws Exception {
   Socket sock = new Socket(args[0], 1234);
   DataInputStream dis = new DataInputStream(sock.getInputStream());
   float f = dis.readFloat();
   System.out.println("PI=" + f);
   dis.close();
   sock.close();
 }

}</source>





Read Object from Socket

   <source lang="java">

import java.io.ObjectInputStream; import java.net.Socket; import java.util.Hashtable; public class Main{

 public static void main(String[] args) throws Exception {
   Socket sock = new Socket(args[0], 1234);
   ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
   Hashtable hash = (Hashtable) ois.readObject();
   System.out.println(hash);
   ois.close();
   sock.close();
 }

}</source>





Socket Info

   <source lang="java">

import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; public class MainClass {

 public static void main(String[] args) {
   try {
     Socket theSocket = new Socket("127.0.0.1", 80);
     System.out.println("Connected to " + theSocket.getInetAddress() + " on port "
         + theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of "
         + theSocket.getLocalAddress());
   } catch (UnknownHostException ex) {
     System.err.println(ex);
   } catch (SocketException ex) {
     System.err.println(ex);
   } catch (IOException ex) {
     System.err.println(ex);
   }
 }

}</source>





Transfer a file via Socket

   <source lang="java">

import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Main {

 public static void main(String[] args) throws IOException {
   ServerSocket servsock = new ServerSocket(123456);
   File myFile = new File("s.pdf");
   while (true) {
     Socket sock = servsock.accept();
     byte[] mybytearray = new byte[(int) myFile.length()];
     BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
     bis.read(mybytearray, 0, mybytearray.length);
     OutputStream os = sock.getOutputStream();
     os.write(mybytearray, 0, mybytearray.length);
     os.flush();
     sock.close();
   }
 }

} The client module import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.Socket; public class Main {

 public static void main(String[] argv) throws Exception {
   Socket sock = new Socket("127.0.0.1", 123456);
   byte[] mybytearray = new byte[1024];
   InputStream is = sock.getInputStream();
   FileOutputStream fos = new FileOutputStream("s.pdf");
   BufferedOutputStream bos = new BufferedOutputStream(fos);
   int bytesRead = is.read(mybytearray, 0, mybytearray.length);
   bos.write(mybytearray, 0, bytesRead);
   bos.close();
   sock.close();
 }

}</source>