public boolean seConnecter() {
    try {
      this.address = InetAddress.getByName(this.serverIpAddress);
      this.requestSocket = new Socket(this.address, this.portCom);
      this.dos = new DataOutputStream(this.requestSocket.getOutputStream());
      if (this.requestSocket.isConnected()) {
        Log.d("Client", "Connection établie");

        Thread envoiThread = new Thread(this);
        envoiThread.start();

        return true;
      } else {
        return false;
      }
    } catch (IOException ioException) {
      ioException.getMessage();
      if (requestSocket.isConnected()) this.seDeconnecter();
      System.err.println("Erreur");
      Log.d("Client", "Erreur Configuration serveur");
      return false;
    } catch (Exception e) {
      if (requestSocket.isConnected()) this.seDeconnecter();
      Log.d("Description Erreur", e.toString());
      return false;
    }
  }
예제 #2
0
  @Override
  protected void onHandleIntent(Intent intent) {

    if (intent.getAction().equals(ACTION_SEND_MESSAGE)) {
      String messageString = intent.getExtras().getString(EXTRAS_MESSSGE_STRING);
      String host = intent.getExtras().getString(EXTRAS_ADDRESS);
      Socket socket = new Socket();
      int port = intent.getExtras().getInt(EXTRAS_PORT);

      try {
        Log.d("MessageTransferService", "Opening client socket - host: " + host);
        socket.bind(null);
        socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
        Log.d("MessageTransferService", "Client socket - " + socket.isConnected());
        OutputStream os = socket.getOutputStream();
        byte[] stringByte = messageString.getBytes();
        os.write(stringByte);
        os.close();
        Log.d("MessageTransferService", "Client: Data written");
      } catch (IOException e) {
        Log.e("MessageTransferService", e.getMessage());
      } finally {
        if (socket != null) {
          if (socket.isConnected()) {
            try {
              socket.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
  }
예제 #3
0
    @Override
    protected Void doInBackground(final Void... unused) {

      Wrapper wrapper = new Wrapper();

      try {
        serverAddress = InetAddress.getByName(Constants.SERVER_IP);
        serverSocket = new Socket();
        serverSocket.connect(
            new InetSocketAddress(Constants.SERVER_IP, Constants.SERVER_PORT), 5000);
      } catch (Exception e) {
        e.printStackTrace();
      }

      wrapper.type = 0;
      wrapper.status = serverSocket.isConnected();
      publishProgress(wrapper);

      try {
        Thread.sleep(500);

        dataInputStream = new DataInputStream(serverSocket.getInputStream());
        dataOutputStream = new DataOutputStream(serverSocket.getOutputStream());

        wrapper.type = 1;

        while (serverSocket.isConnected()) {
          bytes = 0;

          size = dataInputStream.readInt();
          data = new byte[size];

          for (int i = 0; i < size; i += bytes) {
            bytes = dataInputStream.read(data, i, size - i);
          }

          buff = new Mat(1, size, CvType.CV_8UC1);
          buff.put(0, 0, data);

          rev = Highgui.imdecode(buff, Highgui.CV_LOAD_IMAGE_UNCHANGED);

          Imgproc.cvtColor(rev, ret, Imgproc.COLOR_RGB2BGR);

          wrapper.img = ret;
          publishProgress(wrapper);
          Thread.sleep(75);
        }

      } catch (Exception e) {
        e.printStackTrace();
      }

      return null;
    }
예제 #4
0
 @Override
 public boolean disconnect() {
   if (!socket.isConnected()) return false;
   try {
     input.close();
     output.close();
     socket.close();
   } catch (IOException e) {
     Logger.printException(this, e);
   }
   return !socket.isConnected();
 }
  /*
   * (non-Javadoc)
   * @see android.app.IntentService#onHandleIntent(android.content.Intent)
   */
  @Override
  protected void onHandleIntent(Intent intent) {
    Context context = GlobalApplication.getGlobalAppContext();
    if (intent.getAction().equals(FileTransferService.ACTION_SEND_FILE)) {
      String host = intent.getExtras().getString(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS);
      String InetAddress = intent.getExtras().getString(FileTransferService.inetaddress);
      CommonMethods.e("LocalIp Received while first connect", "host address" + host);

      Socket socket = new Socket();
      int port = intent.getExtras().getInt(FileTransferService.EXTRAS_GROUP_OWNER_PORT);

      try {

        Log.d(WiFiDirectActivity.TAG, "Opening client socket for First tiime- ");
        socket.bind(null);
        socket.connect((new InetSocketAddress(host, port)), FileTransferService.SOCKET_TIMEOUT);
        Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
        OutputStream stream = socket.getOutputStream();
        ContentResolver cr = context.getContentResolver();
        InputStream is = null;

        /*
         * Object that is used to send file name with extension and recieved on other side.
         */
        ObjectOutputStream oos = new ObjectOutputStream(stream);
        WiFiTransferModal transObj = new WiFiTransferModal(InetAddress);

        oos.writeObject(transObj);
        System.out.println("Sending request to Socket Server");

        oos.close(); // close the ObjectOutputStream after sending data.
      } catch (IOException e) {
        Log.e(WiFiDirectActivity.TAG, e.getMessage());
        e.printStackTrace();
      } finally {
        if (socket != null) {
          if (socket.isConnected()) {
            try {
              CommonMethods.e("WiFiClientIP Service", "First Connection service socket closed");
              socket.close();
            } catch (Exception e) {
              // Give up
              e.printStackTrace();
            }
          }
        }
      }
    }
  }
예제 #6
0
 @Override
 public void run() {
   while (commandLineSocket.isConnected()) {
     String output = keyboardScanner.nextLine();
     commandLinePrintWriter.println(output);
   }
 }
예제 #7
0
  public static void main(String[] args) throws IOException {
    int queueLenth = 10; // number of clients that can connect at the same time
    int clientPort = 4500; // port that JokeClient and JokeServer communicate on
    Socket socketClient;

    // initialize joke and proverb databases
    Database joke = new JokeDatabase();
    Database proverb = new ProverbDatabase();

    System.out.println("Christian Loera's Joke server, listening at port 4500 and 4891.\n");

    ServerAdmin servAdmin = new ServerAdmin(); // initialize ServerAdmin class
    Thread threadAdmin = new Thread(servAdmin); // create new thread of ServerAdmin class
    threadAdmin
        .start(); // start ServerAdmin thread to handle JokeClientAdmin connection asynchronously

    @SuppressWarnings("resource")
    ServerSocket clientServerSocket =
        new ServerSocket(
            clientPort, queueLenth); // creates socket that binds at port JokeClient connects to

    System.out.println("Client server is running");
    while (true) {
      socketClient = clientServerSocket.accept(); // listening for JokeClient
      if (socketClient
          .isConnected()) // if socketClient connects to JokeClient execute new thread of Worker
      new Worker(socketClient, joke, proverb, mode).start();
    }
  }
  public TCPClient(String userName) throws IOException {

    inFromUser = new BufferedReader(new InputStreamReader(System.in));
    try {
      clientSocket = new Socket("78.91.1.120", 7070);
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    if (clientSocket.isConnected()) {
      System.out.println("halla");
      outToServer = new DataOutputStream(clientSocket.getOutputStream());
      inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      connectToServer();
      while (true) {
        sentence = "MSG " + inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');
        modifiedSentences = inFromServer.readLine();
        System.out.println("FROM SERVER: " + modifiedSentences);
      }
    } else {
      closeConnection();
    }
  }
예제 #9
0
  public void run() {
    // ********************Versão original*********************************
    //    listenSocket(this.host, this.port);
    //	while (socket.isConnected()) {
    //      try {
    //        String line = in.readLine();
    //        String[] params = line.split(" ");
    //        double position = Double.parseDouble(params[0]);
    //        double sumLinePositions = Double.parseDouble(params[1]);
    //        double previousLinePosition = Double.parseDouble(params[2]);
    //        double drive = p * position +
    //                i * sumLinePositions + d * (position - previousLinePosition);
    //        out.println(drive);
    //      } catch (IOException ex) {
    //        Logger.getLogger(RegulatorClient.class.getName()).log(Level.SEVERE, null, ex);
    //        break;
    //      }
    //    }
    // ***********************************************************************

    listenSocket(this.host, this.port);
    while (socket.isConnected()) {
      try {
        double position = Double.parseDouble(in.readLine());

        double drive = 0; // computar usando fazzy

        out.println(drive);
      } catch (IOException ex) {
        Logger.getLogger(RegulatorClient.class.getName()).log(Level.SEVERE, null, ex);
        break;
      }
    }
  }
 public boolean isOpen() {
   return (mIn != null
       && mOut != null
       && mSocket != null
       && mSocket.isConnected()
       && !mSocket.isClosed());
 }
 @Override
 public boolean isConnected() {
   return socket != null
       && !socket.isClosed()
       && socket.isConnected()
       && !socket.isOutputShutdown();
 }
예제 #12
0
  public static void IRCDLinkClose() {
    Logger log = Logger.getLogger("Minecraft");
    if ((server != null) && server.isConnected()) {
      writeSocket(pre + "SQUIT 000 :Shutting down or some shit");
      if (linkcompleted) {
        linkcompleted = false;
      }

      try {
        server.close();
      } catch (IOException e) {
      }
      log.warning("[WIRC] Closed connection to " + Config.remoteHost + ":" + Config.remotePort);
      if (running) {
        log.info(
            "[WIRC] Retrying connection to "
                + Config.remoteHost
                + ":"
                + Config.remotePort
                + " in "
                + Config.reconnectTime
                + " seconds");
        burstPre = false;
        burstSent = false;
        capabSent = false;
        try {
          Thread.sleep(Config.reconnectTime * 100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        IRCDLinkStart();
      }
    }
  }
예제 #13
0
  @Override
  public void run() {

    try {

      while (true) {
        while (socket.getInputStream().available() == 0 && socket.isConnected()) {
          Thread.sleep(1);
        }

        int size = socket.getInputStream().available();

        byte[] buffer = new byte[size];

        socket.getInputStream().read(buffer, 0, size);

        for (OnDataCallback callback : OnData) {
          callback.onData(this, buffer);
        }
      }

    } catch (Exception e) {

      e.printStackTrace();

      for (OnCloseCallback callback : OnClose) {
        callback.onClose(this);
      }
    }
  }
예제 #14
0
 /** {@inheritDoc} */
 @Override
 public AsyncSocketChannelImpl shutdown(ShutdownType how) throws IOException {
   final Socket socket = channel.socket();
   try {
     if (how == ShutdownType.READ || how == ShutdownType.BOTH) {
       if (!socket.isInputShutdown()) {
         socket.shutdownInput();
         key.selected(OP_READ);
       }
     }
     if (how == ShutdownType.WRITE || how == ShutdownType.BOTH) {
       if (!socket.isOutputShutdown()) {
         socket.shutdownOutput();
         key.selected(OP_WRITE);
       }
     }
   } catch (SocketException e) {
     if (!socket.isConnected()) {
       throw Util.initCause(new NotYetConnectedException(), e);
     }
     if (socket.isClosed()) {
       throw Util.initCause(new ClosedChannelException(), e);
     }
     throw e;
   }
   return this;
 }
  public void server() {
    try {
      ss = new ServerSocket(5000);
      socket = ss.accept();
      System.out.println(socket);
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(socket.getOutputStream(), true);
      while (socket.isConnected()) {

        String line = in.readLine();
        System.out.println(line);
        out.println("you input is :" + line);
      }
      out.close();
      in.close();
      socket.close();
    } catch (IOException e) {

    } finally {
      try {
        ss.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
예제 #16
0
  public PircTestRunner(Configuration.Builder config) throws IOException, IrcException {
    ACTIVE_INSTANCE_COUNT++;

    InetAddress address = InetAddress.getByName("127.1.1.1");
    Socket socket = mock(Socket.class);
    when(socket.isConnected()).thenReturn(true);
    when(socket.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0]));
    when(socket.getOutputStream()).thenReturn(new ByteArrayOutputStream());
    SocketFactory socketFactory = mock(SocketFactory.class);
    when(socketFactory.createSocket(eq(address), anyInt(), eq((InetAddress) null), eq(0)))
        .thenReturn(socket);
    config.setSocketFactory(socketFactory);

    config.setListenerManager(
        new GenericListenerManager() {
          final Logger log = LoggerFactory.getLogger(getClass());

          @Override
          public void onEvent(Event event) {
            log.debug("Dispatched event " + event);
            eventQueue.addLast(event);
          }
        });

    in = new FakeReader();

    bot = new CapturedPircBotX(config.buildConfiguration());
    bot.startBot();
  }
예제 #17
0
 /**
  * 入力データからパケットを構築して送信する。今回はSocketを複数開いたり、 ということは起こらないので本メソッドに集約してしまってる。空文字列が送られてきたら
  * 特殊パターンとしてrefresh用のパケットを構築する(つまり\0単独は特殊パターン)
  *
  * @return 正常終了時は0。サーバへの接続が失われていれば-4。その他I/Oエラー時は-1。
  */
 private int sendPacket(String src) {
   OutputStream writer;
   Log.d("moku99", "sending a packet");
   try {
     if (clientSock.isConnected() == false) {
       return -4;
     }
     writer = clientSock.getOutputStream();
     if (src.equals("")) {
       // 空の特殊パターン
       ByteBuffer buf = ByteBuffer.allocate(8);
       buf.putInt(myId.intValue());
       buf.putInt(0);
       writer.write(buf.array());
     } else {
       // 通常メッセージ送信パターン
       byte[] strBuf = src.getBytes();
       ByteBuffer buf = ByteBuffer.allocate(8 + strBuf.length);
       buf.putInt(myId.intValue());
       buf.putInt(strBuf.length);
       buf.put(strBuf);
       writer.write(buf.array());
     }
   } catch (IOException e) {
     Log.d("moku99", e.getLocalizedMessage());
     return -1;
   }
   return 0;
 }
예제 #18
0
파일: Main.java 프로젝트: ralmn/ChatClient
  @SuppressWarnings("static-access")
  public static void Login(String ip, String login) {
    chat.menuItem1.setEnabled(false);
    chat.setDefaultCloseOperation(chat.EXIT_ON_CLOSE);

    int port = 30000;

    if (ip.contains(":")) {
      String p = ip.split(":")[1];
      port = Integer.parseInt(p);
    }

    try {
      socket = new Socket(ip, port);
    } catch (Exception e) {
      write("<font color=red><b> Le serveur <i>" + ip + "</i> est indisponible </b> </font> ");
      chat.menuItem1.setEnabled(true);
      return;
    }
    if (!socket.isConnected()) {
      System.out.println("Erreur");
    }
    t1 = new Thread(new Connexion(socket, login));
    t1.start();
  }
  protected Socket borrowSocket() throws IOException {
    Socket socket = socketBlockingQueue.poll();

    if (socket != null) {
      if (socket.isClosed()
          || !socket.isConnected()
          || socket.isInputShutdown()
          || socket.isOutputShutdown()) {

        try {
          socket.close();
        } catch (IOException ioe) {
          if (_log.isWarnEnabled()) {
            _log.warn(ioe, ioe);
          }
        }

        socket = null;
      }
    }

    if (socket == null) {
      socket = new Socket();

      socket.connect(socketAddress);
    }

    return socket;
  }
 /**
  * Check if the Socket is still connected
  *
  * @return true if a connection is established
  */
 public boolean isConnected() {
   if (mSocket == null || !mSocket.isConnected()) {
     return false;
   } else {
     return true;
   }
 }
예제 #21
0
 private Socket getSocket(InetAddress addr, int portNo) {
   Socket socket = null;
   if (sockets.containsKey(addr) == true) {
     socket = sockets.get(addr);
     // check the status of the socket
     if (socket.isConnected() == false
         || socket.isInputShutdown() == true
         || socket.isOutputShutdown() == true
         || socket.getPort() != portNo) {
       // if socket is not suitable, then create a new socket
       sockets.remove(addr);
       try {
         socket.shutdownInput();
         socket.shutdownOutput();
         socket.close();
         socket = new Socket(addr, portNo);
         sockets.put(addr, socket);
       } catch (IOException e) {
         Log.e("getSocket: when closing and removing", "");
       }
     }
   } else {
     try {
       socket = new Socket(addr, portNo);
       sockets.put(addr, socket);
     } catch (IOException e) {
       Log.e("getSocket: when creating", "");
     }
   }
   return socket;
 }
예제 #22
0
파일: TestSocket.java 프로젝트: stxyg/demo
  public static void main(String[] args) throws IOException {
    Socket s = new Socket();
    s.connect(new InetSocketAddress("www.meizu.com", 80), 2000);
    // s.setSoTimeout(2000);
    boolean b = s.isConnected();
    System.out.println(b);
    if (b) {
      InputStream in = s.getInputStream();
      System.out.println(in);
      Scanner scanner = new Scanner(in);
      byte[] buf = new byte[1024];
      System.out.println(in.available());
      System.out.println((in.read(buf) != -1));
      while (in.read(buf) != -1) {
        System.out.println("in...");
        System.out.println(buf);
      }

      while (scanner.hasNext()) {
        System.out.println("有数据。。。。");
        String next = scanner.nextLine();

        System.out.println(next);
      }
      s.close();
      if (s.isClosed()) {
        System.out.println("套接字已经关闭");
      }
    }
  }
  @Override
  public void onCreate() {
    Log.i(TAG, "inside onCreate - Creating Socket");
    super.onCreate();
    if (mSocket == null || mSocket.isClosed()) {
      try {
        // mSocket = new Socket(InetAddress.getByName("localhost"), 7201);
        mSocket = new Socket();
        Log.d(TAG, "Opening client socket - ");
        mSocket.bind(null);

        mSocket.connect(
            (new InetSocketAddress(
                getString(R.string.queue_server_dns),
                getResources().getInteger(R.integer.next_token_port))),
            SOCKET_TIMEOUT);

        Log.d(TAG, "Client socket - " + mSocket.isConnected());
        assert mSocket != null;
        mDataInputStream = new DataInputStream(mSocket.getInputStream());
        Log.i(TAG, "Socket Created, Stream Opened");
      } catch (UnknownHostException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (IOException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      }
    }
  }
예제 #24
0
  void test() throws Exception {
    InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort);
    Proxy httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);

    try (ServerSocket ss = new ServerSocket(0);
        Socket sock = new Socket(httpProxy)) {
      sock.setSoTimeout(SO_TIMEOUT);
      sock.setTcpNoDelay(false);

      InetSocketAddress externalAddress =
          new InetSocketAddress(InetAddress.getLocalHost(), ss.getLocalPort());

      out.println("Trying to connect to server socket on " + externalAddress);
      sock.connect(externalAddress);
      try (Socket externalSock = ss.accept()) {
        // perform some simple checks
        check(sock.isBound(), "Socket is not bound");
        check(sock.isConnected(), "Socket is not connected");
        check(!sock.isClosed(), "Socket should not be closed");
        check(sock.getSoTimeout() == SO_TIMEOUT, "Socket should have a previously set timeout");
        check(sock.getTcpNoDelay() == false, "NODELAY should be false");

        simpleDataExchange(sock, externalSock);
      }
    }
  }
예제 #25
0
파일: Server.java 프로젝트: hvram1/bankdemo
 public void run() {
   int count = 0;
   byte[] lenbuf = new byte[2];
   try {
     // For high volume apps you will be better off only reading the
     // stream in this thread
     // and then using another thread to parse the buffers and process
     // the requests
     // Otherwise the network buffer might fill up and you can miss a
     // request.
     while (socket != null
         && socket.isConnected()
         && Thread.currentThread().isAlive()
         && !Thread.currentThread().isInterrupted()) {
       if (socket.getInputStream().read(lenbuf) == 2) {
         int size = ((lenbuf[0] & 0xff) << 8) | (lenbuf[1] & 0xff);
         byte[] buf = new byte[size];
         // We're not expecting ETX in this case
         socket.getInputStream().read(buf);
         count++;
         // Set a job to parse the message and respond
         // Delay it a bit to pretend we're doing something important
         threadPool.schedule(new Processor(buf, socket), 400, TimeUnit.MILLISECONDS);
       }
     }
   } catch (IOException ex) {
     log.error("Exception occurred...", ex);
   }
   log.debug(String.format("Exiting after reading %d requests", count));
   try {
     socket.close();
   } catch (IOException ex) {
   }
 }
예제 #26
0
  public static boolean isPortAvailable(int port) {
    boolean available = true;

    int available_code = mOpenPorts.get(port);

    if (available_code != 0) return available_code != 1;

    try {
      // attempt 3 times since proxy and server could be still releasing
      // their ports
      for (int i = 0; i < 3; i++) {
        Socket channel = new Socket();
        InetSocketAddress address =
            new InetSocketAddress(InetAddress.getByName(mNetwork.getLocalAddressAsString()), port);

        channel.connect(address, 200);

        available = !channel.isConnected();

        channel.close();

        if (available) break;

        Thread.sleep(200);
      }
    } catch (Exception e) {
      available = true;
    }

    mOpenPorts.put(port, available ? 2 : 1);

    return available;
  }
예제 #27
0
 /**
  * Creates a SocksSocket instance with a {@link SocksProxy} and a
  *
  * @param proxy SOCKS proxy.
  * @param proxySocket a unconnected socket. it will connect SOCKS server later.
  */
 public SocksSocket(SocksProxy proxy, Socket proxySocket) {
   checkNotNull(proxy, "Argument [proxy] may not be null");
   checkNotNull(proxySocket, "Argument [proxySocket] may not be null");
   checkArgument(!proxySocket.isConnected(), "Proxy socket should be unconnected");
   this.proxySocket = proxySocket;
   this.proxy = proxy.copy();
   this.proxy.setProxySocket(proxySocket);
 }
 public boolean validateObject(Object key, Object value) {
   SocketAndStreams sands = (SocketAndStreams) value;
   Socket s = sands.getSocket();
   boolean isValid = !s.isClosed() && s.isBound() && s.isConnected();
   if (!isValid && logger.isDebugEnabled())
     logger.debug("Socket connection " + sands + " is no longer valid, closing.");
   return isValid;
 }
 private void reconnect() throws IOException {
   if (socket == null) {
     connect();
   } else if (socket.isClosed() || (!socket.isConnected())) {
     close();
     connect();
   }
 }
예제 #30
0
 // @override
 @Override
 public void run() {
   Thread.currentThread().setName("SparshUI Client->ServerConnection");
   while (_socket.isConnected()) {
     if (!_protocol.processRequest(_client)) // BH -- must allow for server failure
     break;
   }
 }