Advertisement
Guest User

Untitled

a guest
May 13th, 2012
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. package com.client.core;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5.  
  6. public class SocketManager implements Runnable {
  7.    
  8.     private Socket sock;
  9.     private PrintWriter output;
  10.     private BufferedReader input;
  11.     private String hostname;
  12.     private int portnumber;
  13.    
  14.     public SocketManager(String ip, int port){
  15.         try{
  16.             sock = new Socket(ip,port);
  17.             hostname = ip;
  18.             portnumber = port;
  19.         }catch(Exception e){
  20.             System.out.println("Client: Socket failed to connect.");
  21.         }
  22.     }
  23.    
  24.    
  25.    
  26.     public synchronized void send(String data){
  27.         try{
  28.             output.println(data);
  29.             output.flush();
  30.         }catch(Exception e){
  31.            
  32.         }
  33.     }
  34.    
  35.     public synchronized void connect(){
  36.         try{
  37.             sock = new Socket(hostname,portnumber);
  38.            
  39.         }catch(Exception e){
  40.            
  41.         }
  42.     }
  43.    
  44.     public synchronized Socket getSocket(){
  45.         return sock;
  46.     }
  47.    
  48.     public synchronized void connect(String host, int port){
  49.         try{
  50.             sock = new Socket(host, port);
  51.            
  52.         }catch(Exception e){
  53.            
  54.         }
  55.     }
  56.    
  57.     public synchronized void close(){
  58.         try{
  59.             sock.close();
  60.         }catch(Exception e){
  61.            
  62.         }
  63.         output = null;
  64.         input = null;
  65.         System.gc();
  66.     }
  67.    
  68.     public void listenStream(){
  69.         try {
  70.             while(input.ready()){
  71.                 System.out.println(input.readLine());
  72.             }
  73.         } catch (Exception e) {
  74.        
  75.         }
  76.     }
  77.  
  78.     @Override
  79.     public void run() {
  80.         try{
  81.             output = new PrintWriter(sock.getOutputStream());
  82.             input = new BufferedReader(
  83.                     new InputStreamReader(sock.getInputStream()));
  84.         }catch(Exception e){
  85.            
  86.         }
  87.         listenStream();
  88.        
  89.     }
  90.  
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement