Advertisement
Guest User

Untitled

a guest
Aug 25th, 2011
801
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.08 KB | None | 0 0
  1. package hardy.scl.communication;
  2.  
  3. import hardy.scl.interfaces.IAppManager;
  4. import hardy.scl.interfaces.ISocketOperator;
  5.  
  6. import java.io.BufferedInputStream;
  7. import java.io.BufferedOutputStream;
  8. import java.io.BufferedReader;
  9. import java.io.File;
  10. import java.io.FileInputStream;
  11. import java.io.FileNotFoundException;
  12. import java.io.IOException;
  13. import java.io.InputStream;
  14. import java.io.InputStreamReader;
  15. import java.io.OutputStream;
  16. import java.io.OutputStreamWriter;
  17. import java.io.PrintWriter;
  18. import java.net.HttpURLConnection;
  19. import java.net.InetAddress;
  20. import java.net.MalformedURLException;
  21. import java.net.ServerSocket;
  22. import java.net.Socket;
  23. import java.net.URL;
  24. import java.net.UnknownHostException;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27.  
  28. import android.util.Log;
  29.  
  30.  
  31. public class SocketOperator implements ISocketOperator
  32. {
  33.     private static final String AUTHENTICATION_SERVER_ADDRESS = "http://10.10.10.100/chippers/";
  34.  
  35.     private int listeningPort = 0;
  36.  
  37.     private static final String HTTP_REQUEST_FAILED = null;
  38.  
  39.  
  40.  
  41.     private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
  42.  
  43.     private ServerSocket serverSocket = null;
  44.  
  45.     private boolean listening;
  46.  
  47.     private IAppManager appManager;
  48.  
  49.     public int filesize ;
  50.  
  51.  
  52.  
  53.     private class ReceiveFileConnection extends Thread {
  54.         Socket clientSocket = null;
  55.         Socket fileSocket=null;
  56.         public ReceiveConnection(Socket socket)
  57.         {
  58.             this.fileSocket=socket;
  59.             SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
  60.         }
  61.  
  62.         @Override
  63.             public void run() {
  64.             try {
  65.                 InputStream is=fileSocket.getInputStream();
  66.                 appManager.fileReceived(is);
  67.                 fileSocket.close();
  68.             } catch (IOException e) {
  69.                 Log.e("ReceiveConnection.run: when receiving connection ","");
  70.             }          
  71.         }  
  72.     }
  73.  
  74.     private class ReceiveMessageConnection extends Thread {
  75.         Socket clientSocket = null;
  76.         public ReceiveConnection(Socket socket)
  77.         {
  78.             this.clientSocket = socket;
  79.             SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
  80.         }
  81.  
  82.         @Override
  83.             public void run() {
  84.             try {
  85.                 BufferedReader in = new BufferedReader(new InputStreamReader(
  86.                             clientSocket.getInputStream()))
  87.                 String inputLine;
  88.                 while ((inputLine = in.readLine()) != null) {
  89.                     appManager.messageReceived(inputLine);
  90.                 }
  91.                 clientSocket.close();
  92.             } catch (IOException e) {
  93.                 Log.e("ReceiveConnection.run: when receiving connection ","");
  94.             }          
  95.         }  
  96.     }
  97.  
  98.  
  99.     public SocketOperator(IAppManager appManager) {
  100.         this.appManager = appManager;  
  101.     }
  102.  
  103.  
  104.     public String sendHttpRequest(String params)
  105.     {      
  106.         URL url;
  107.         String result = new String();
  108.         try
  109.             {
  110.                 url = new URL(AUTHENTICATION_SERVER_ADDRESS);
  111.                 HttpURLConnection connection;
  112.                 connection = (HttpURLConnection) url.openConnection();
  113.                 connection.setDoOutput(true);
  114.  
  115.                 PrintWriter out = new PrintWriter(connection.getOutputStream());
  116.  
  117.                 out.println(params);
  118.                 out.close();
  119.  
  120.                 BufferedReader in = new BufferedReader(
  121.                                                        new InputStreamReader(
  122.                                                                              connection.getInputStream()));
  123.                 String inputLine;
  124.  
  125.                 while ((inputLine = in.readLine()) != null) {
  126.                     result = result.concat(inputLine);              
  127.                 }
  128.                 in.close();        
  129.             }
  130.         catch (MalformedURLException e) {
  131.             e.printStackTrace();
  132.         }
  133.         catch (IOException e) {
  134.             e.printStackTrace();
  135.         }          
  136.  
  137.         if (result.length() == 0) {
  138.             result = HTTP_REQUEST_FAILED;
  139.         }
  140.  
  141.         return result;
  142.  
  143.  
  144.     }
  145.  
  146.  
  147.     public boolean sendMessage(String message, String ip, int port)
  148.     {
  149.         try {
  150.  
  151.  
  152.             String[] str = ip.split("\\.");
  153.  
  154.             byte[] IP = new byte[str.length];
  155.  
  156.             for (int i = 0; i < str.length; i++) {
  157.  
  158.                 IP[i] = (byte) Integer.parseInt(str[i]);                
  159.             }
  160.             Socket socket = getSocket(InetAddress.getByAddress(IP), port);
  161.             if (socket == null) {
  162.                 return false;
  163.             }
  164.  
  165.             PrintWriter out = null;
  166.             out = new PrintWriter(socket.getOutputStream(), true);
  167.             //OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());
  168.             //outputStream.write("Text");
  169.             // outputStream.flush();
  170.             String flag = "Text";
  171.             message = message+flag;
  172.             out.println(message);
  173.         } catch (UnknownHostException e) {          
  174.             return false;
  175.             //e.printStackTrace();
  176.         } catch (IOException e) {
  177.             return false;          
  178.             //e.printStackTrace();
  179.         }
  180.  
  181.         return true;        
  182.     }
  183.  
  184.  
  185.  
  186.  
  187.     public int startListening(int portNo, boolean isMessageListening)
  188.     {
  189.         listening = true;
  190.  
  191.         try {
  192.             serverSocket = new ServerSocket(portNo);
  193.             this.listeningPort = portNo;
  194.         } catch (IOException e) {          
  195.  
  196.             //e.printStackTrace();
  197.             this.listeningPort = 0;
  198.             return 0;
  199.         }
  200.  
  201.         while (listening) {
  202.             try {
  203.                 if (isMessageListening) {
  204.                     new ReceiveMessageConnection(serverSocket.accept()).start();
  205.                 } else {
  206.                     new ReceiveFileConnectino(serverSocket.accept()).start();
  207.                 }
  208.  
  209.             } catch (IOException e) {
  210.                 //e.printStackTrace();              
  211.                 return 2;
  212.             }
  213.         }
  214.  
  215.         try {
  216.             serverSocket.close();
  217.         } catch (IOException e) {          
  218.             Log.e("Exception server socket", "Exception when closing server socket");
  219.             return 3;
  220.         }
  221.  
  222.  
  223.         return 1;
  224.     }
  225.  
  226.  
  227.     public void stopListening()
  228.     {
  229.         this.listening = false;
  230.     }
  231.  
  232.     private Socket getSocket(InetAddress addr, int portNo)
  233.     {
  234.         Socket socket = null;
  235.         if (sockets.containsKey(addr) == true)
  236.             {
  237.                 socket = sockets.get(addr);
  238.                 // check the status of the socket
  239.                 if  ( socket.isConnected() == false ||
  240.                       socket.isInputShutdown() == true ||
  241.                       socket.isOutputShutdown() == true ||
  242.                       socket.getPort() != portNo
  243.                       )  
  244.                     {          
  245.                         // if socket is not suitable,  then create a new socket
  246.                         sockets.remove(addr);              
  247.                         try {
  248.                             socket.shutdownInput();
  249.                             socket.shutdownOutput();
  250.                             socket.close();
  251.                             socket = new Socket(addr, portNo);
  252.                             sockets.put(addr, socket);
  253.                         }
  254.                         catch (IOException e) {                
  255.                             Log.e("getSocket: when closing and removing", "");
  256.                         }              
  257.                     }
  258.             }
  259.         else  
  260.             {
  261.                 try {
  262.                     socket = new Socket(addr, portNo);
  263.                     sockets.put(addr, socket);
  264.                 } catch (IOException e) {
  265.                     Log.e("getSocket: when creating", "");              
  266.                 }                  
  267.             }
  268.         return socket;      
  269.     }
  270.  
  271.  
  272.     public void exit()
  273.     {          
  274.         for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
  275.             {
  276.                 Socket socket = (Socket) iterator.next();
  277.                 try {
  278.                     socket.shutdownInput();
  279.                     socket.shutdownOutput();
  280.                     socket.close();
  281.                 } catch (IOException e)
  282.                     {              
  283.                     }      
  284.             }
  285.  
  286.         sockets.clear();
  287.         this.stopListening();
  288.         appManager = null;
  289.         //      timer.cancel();    
  290.     }
  291.  
  292.  
  293.     public int getListeningPort() {
  294.  
  295.         return this.listeningPort;
  296.     }
  297.  
  298.  
  299.     @Override
  300.         public boolean sendFile(String ip, int port) {
  301.         // TODO Auto-generated method stub
  302.  
  303.  
  304.         try {
  305.  
  306.  
  307.             String[] str = ip.split("\\.");
  308.  
  309.             byte[] IP = new byte[str.length];
  310.  
  311.             for (int i = 0; i < str.length; i++) {
  312.  
  313.                 IP[i] = (byte) Integer.parseInt(str[i]);
  314.  
  315.  
  316.             }
  317.             Socket socket = getSocket(InetAddress.getByAddress(IP), port);
  318.             if (socket == null) {
  319.                 return false;
  320.             }
  321.             Log.i("SocketOP", "sendFILE-1");
  322.             File  f = new File("/sdcard/chats/gas.jpg/");
  323.  
  324.             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
  325.             int readData;
  326.             byte[] buffer = new byte[1024];  
  327.             bis.read(buffer, 0,buffer.length);
  328.             OutputStream os = socket.getOutputStream();
  329.  
  330.             while((readData=bis.read(buffer))!=-1){
  331.                 os.write(buffer,0,readData);
  332.  
  333.  
  334.                 Log.i("SocketOP", "sendFILE-3");
  335.             }
  336.  
  337.         } catch (IOException e) {
  338.             return false;          
  339.             //e.printStackTrace();
  340.         }
  341.         //  Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
  342.  
  343.         return true;        
  344.     }
  345. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement