Advertisement
Guest User

Untitled

a guest
May 19th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. package ca.frozen.rpicameraviewer.classes;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.InetSocketAddress;
  6. import java.net.Socket;
  7.  
  8. import ca.frozen.library.classes.Log;
  9.  
  10. public class TcpIpReader
  11. {
  12.     // public constants
  13.     public final static int IO_TIMEOUT = 1000;
  14.  
  15.     // local constants
  16.     private final static int CONNECT_TIMEOUT = 5000;
  17.  
  18.     // instance variables
  19.     private Socket socket = null;
  20.     private InputStream inputStream = null;
  21.  
  22.     public TcpIpReader(Camera camera)
  23.     {
  24.         try
  25.         {
  26.             socket = getConnection(camera.address, camera.port, CONNECT_TIMEOUT);
  27.             socket.setSoTimeout(IO_TIMEOUT);
  28.             inputStream = socket.getInputStream();
  29.         }
  30.         catch (Exception ex) {}
  31.     }
  32.  
  33.     public int read(byte[] buffer)
  34.     {
  35.         try
  36.         {
  37.             return (inputStream != null) ? inputStream.read(buffer) : 0;
  38.         }
  39.         catch (IOException ex)
  40.         {
  41.             return 0;
  42.         }
  43.     }
  44.  
  45.     public boolean isConnected()
  46.     {
  47.         return (socket != null) && socket.isConnected();
  48.     }
  49.  
  50.     public void close()
  51.     {
  52.         if (inputStream != null)
  53.         {
  54.             try
  55.             {
  56.                 inputStream.close();
  57.             }
  58.             catch (Exception ex) {}
  59.             inputStream = null;
  60.         }
  61.         if (socket != null)
  62.         {
  63.             try
  64.             {
  65.                 socket.close();
  66.             }
  67.             catch (Exception ex) {}
  68.             socket = null;
  69.         }
  70.     }
  71.  
  72.     public static Socket getConnection(String baseAddress, int port, int timeout)
  73.     {
  74.         Socket socket;
  75.         try
  76.         {
  77.             socket = new Socket();
  78.             InetSocketAddress socketAddress = new InetSocketAddress(baseAddress, port);
  79.             socket.connect(socketAddress, timeout);
  80.         }
  81.         catch (Exception ex)
  82.         {
  83.             Log.info("TcpIp getConnection: " + ex.toString());
  84.             socket = null;
  85.         }
  86.         return socket;
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement