コード例 #1
0
ファイル: Server.java プロジェクト: piyushagade/BitSync
  public static void main(String args[]) throws IOException {
    ServerSocket sSocket = new ServerSocket(sPort, 10);

    // Arguments Handling
    if (args.length != 1) {
      System.out.println("Must specify a file-path argument.");
    } else {
      String currentDir = System.getProperty("user.dir");
      filePath = currentDir + "/src/srcFile/" + args[0];
      filename = args[0];
    }

    // Get list of chunks owned
    chunkOwned();

    // Call FileSplitter
    FileSplitter fs = new FileSplitter();
    fs.split(filePath);

    System.out.println("Waiting for connection");
    while (true) {
      Socket connection = sSocket.accept();
      System.out.println("Connection received from " + connection.getInetAddress().getHostName());

      new Thread(new MultiThreadServer(connection)).start();
    }
  }
コード例 #2
0
ファイル: Server.java プロジェクト: piyushagade/BitSync
  @Override
  public void run() {
    try {
      out = new ObjectOutputStream(csocket.getOutputStream());
      out.flush();
      in = new ObjectInputStream(csocket.getInputStream());

      // Look for chunks
      String currentDir = System.getProperty("user.dir");
      File folder = new File(currentDir + "/src/srcFile");
      File[] listOfFiles = folder.listFiles();
      int fileCount = 0;
      OutputStream os;
      for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()
            && listOfFiles[i]
                .getName()
                .toLowerCase()
                .contains("chunk")) { // 0 1 10 11 12 13 14 2 20 21 22 23 3 4 5 ....
          fileCount++;
          String chunkName = listOfFiles[i].getName().toString();
          chunkId = chunkName.substring(chunkName.lastIndexOf('.') + 6);

          xPayload(chunkId);
          if ((connTo.equals("2") && Integer.parseInt(chunkId) % noDev == 0)
              || (connTo.equals("3") && (Integer.parseInt(chunkId) - 1) % noDev == 0)
              || (connTo.equals("4") && (Integer.parseInt(chunkId) - 2) % noDev == 0)
              || (connTo.equals("5") && (Integer.parseInt(chunkId) - 3) % noDev == 0)
              || (connTo.equals("6") && (Integer.parseInt(chunkId) - 4) % noDev == 0)) {

            System.out.println(chunkName);
            sendFile(chunkName);
          }
        }
      }

      xPayload("-1");
      System.out.println("All chunks sent.");

    } catch (IOException ioException) {
      ioException.printStackTrace();
    } finally {
      // Close connections
      try {
        in.close();
        out.close();
        csocket.close();
        System.out.println("Thread closed.");
      } catch (IOException ioException) {
        System.out.println("Client " + devId + " disconnected.");
      }
    }
  }
コード例 #3
0
ファイル: Server.java プロジェクト: piyushagade/BitSync
  // Send File
  public void sendFile(String chunkName) throws IOException {
    OutputStream os = null;
    String currentDir = System.getProperty("user.dir");
    chunkName = currentDir + "/src/srcFile/" + chunkName;
    File myFile = new File(chunkName);

    byte[] arrby = new byte[(int) myFile.length()];

    try {
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(arrby, 0, arrby.length);

      os = csocket.getOutputStream();
      System.out.println("Sending File.");
      os.write(arrby, 0, arrby.length);
      os.flush();
      System.out.println("File Sent.");
      //			os.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //			os.close();
    }
  }
コード例 #4
0
ファイル: Speed.java プロジェクト: xzhixian/event.java
  static void classicClient() {
    try {
      Socket s = new Socket("localhost", 4321);

      OutputStream os = s.getOutputStream();
      InputStream is = s.getInputStream();

      os.write("hello".getBytes());

      int i = 0;
      while (-1 != (i = is.read())) {
        os.write(i);
      }
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
コード例 #5
0
    public void sendMessage(Address address, byte[] message) throws java.io.IOException {
      Socket s = null;
      SocketEntry entry = (SocketEntry) sockets.get(address);
      if (logger.isDebugEnabled()) {
        logger.debug("Looking up connection for destination '" + address + "' returned: " + entry);
        logger.debug(sockets.toString());
      }
      if (entry != null) {
        s = entry.getSocket();
      }
      if ((s == null) || (s.isClosed())) {
        if (logger.isDebugEnabled()) {
          logger.debug("Socket for address '" + address + "' is closed, opening it...");
        }
        SocketChannel sc = null;
        try {
          // Open the channel, set it to non-blocking, initiate connect
          sc = SocketChannel.open();
          sc.configureBlocking(false);
          sc.connect(
              new InetSocketAddress(
                  ((TcpAddress) address).getInetAddress(), ((TcpAddress) address).getPort()));
          s = sc.socket();
          entry = new SocketEntry((TcpAddress) address, s);
          entry.addMessage(message);
          sockets.put(address, entry);

          synchronized (pending) {
            pending.add(entry);
          }

          selector.wakeup();
          logger.debug("Trying to connect to " + address);
        } catch (IOException iox) {
          logger.error(iox);
          throw iox;
        }
      } else {
        entry.addMessage(message);
        synchronized (pending) {
          pending.add(entry);
        }
        selector.wakeup();
      }
    }
コード例 #6
0
ファイル: JavaNewIO.java プロジェクト: juniuszhou/java
  public void run() {
    try {
      SocketChannel sc = SocketChannel.open();
      InetSocketAddress sinaAddr = new InetSocketAddress("sina.com", 80);
      sc.socket().connect(sinaAddr);

      // init a selector via helper class selector provider
      Selector aSel = SelectorProvider.provider().openSelector();

      Socket soc = new Socket("host", 80);
      soc.getChannel().register(aSel, SelectionKey.OP_ACCEPT);

      // init a channel for server socket. method 1
      ServerSocketChannel ssc = ServerSocketChannel.open();
      ssc.configureBlocking(true);

      // method 2, get server socket first, then init its channel
      ServerSocket ss = new ServerSocket();
      ServerSocketChannel ssc2 = ss.getChannel();

      // set socket channel as non blocking.
      ssc.configureBlocking(false);

      InetSocketAddress isa = new InetSocketAddress("localhost", 9999);
      ssc.socket().bind(isa);

      SelectionKey acceptKey = ssc.register(aSel, SelectionKey.OP_ACCEPT);
      int keysAdded = 0;
      while ((keysAdded = aSel.select()) > 0) {
        Set readyKeys = aSel.selectedKeys();
        Iterator i = readyKeys.iterator();
        while (i.hasNext()) {
          SelectionKey sk = (SelectionKey) i.next();
          i.remove();
          ServerSocketChannel n = (ServerSocketChannel) sk.channel();
          // now we got a new socket and its channel after accept in server
          Socket s = n.accept().socket();
          SocketChannel socketChannel = s.getChannel();
          socketChannel.register(aSel, SelectionKey.OP_READ);
        }
      }
    } catch (Exception e) {

    }
  }
コード例 #7
0
ファイル: JavaNewIO.java プロジェクト: juniuszhou/java
  public void run() {
    try {

      sc = new Socket();
      InetSocketAddress isa = new InetSocketAddress("localhost", 9999);
      sc.connect(isa);
      OutputStream ost = sc.getOutputStream();

      for (int i = 0; i < 10; ++i) {
        String str = "client interation " + (new Integer(i)).toString();
        ost.write(str.getBytes());
        ost.flush();
        System.out.println("Client at " + (new Integer(i)).toString());
        sleep(1000);
      }
    } catch (Exception e) {
    }
  }
コード例 #8
0
 public InetSocketAddress getLocalAddress() {
   Socket s = connection.getChannel().socket();
   InetAddress ia = s.getLocalAddress();
   int port = s.getLocalPort();
   return new InetSocketAddress(ia, port);
 }
コード例 #9
0
    public void run() {
      // Here's where everything happens. The select method will
      // return when any operations registered above have occurred, the
      // thread has been interrupted, etc.
      try {
        while (!stop) {
          try {
            if (selector.select() > 0) {
              if (stop) {
                break;
              }
              // Someone is ready for I/O, get the ready keys
              Set readyKeys = selector.selectedKeys();
              Iterator it = readyKeys.iterator();

              // Walk through the ready keys collection and process date requests.
              while (it.hasNext()) {
                SelectionKey sk = (SelectionKey) it.next();
                it.remove();
                SocketChannel readChannel = null;
                TcpAddress incomingAddress = null;
                if (sk.isAcceptable()) {
                  // The key indexes into the selector so you
                  // can retrieve the socket that's ready for I/O
                  ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel();
                  // Accept the date request and send back the date string
                  Socket s = nextReady.accept().socket();
                  readChannel = s.getChannel();
                  readChannel.configureBlocking(false);
                  readChannel.register(selector, SelectionKey.OP_READ);

                  incomingAddress = new TcpAddress(s.getInetAddress(), s.getPort());
                  SocketEntry entry = new SocketEntry(incomingAddress, s);
                  sockets.put(incomingAddress, entry);
                  timeoutSocket(entry);
                  TransportStateEvent e =
                      new TransportStateEvent(
                          DefaultTcpTransportMapping.this,
                          incomingAddress,
                          TransportStateEvent.STATE_CONNECTED,
                          null);
                  fireConnectionStateChanged(e);
                } else if (sk.isReadable()) {
                  readChannel = (SocketChannel) sk.channel();
                  incomingAddress =
                      new TcpAddress(
                          readChannel.socket().getInetAddress(), readChannel.socket().getPort());
                } else if (sk.isWritable()) {
                  try {
                    SocketEntry entry = (SocketEntry) sk.attachment();
                    SocketChannel sc = (SocketChannel) sk.channel();
                    if (entry != null) {
                      writeMessage(entry, sc);
                    }
                  } catch (IOException iox) {
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_DISCONNECTED_REMOTELY,
                            iox);
                    fireConnectionStateChanged(e);
                    sk.cancel();
                  }
                } else if (sk.isConnectable()) {
                  try {
                    SocketEntry entry = (SocketEntry) sk.attachment();
                    SocketChannel sc = (SocketChannel) sk.channel();
                    if ((!sc.isConnected()) && (sc.finishConnect())) {
                      sc.configureBlocking(false);
                      logger.debug("Connected to " + entry.getPeerAddress());
                      // make sure conncetion is closed if not used for timeout
                      // micro seconds
                      timeoutSocket(entry);
                      sc.register(selector, SelectionKey.OP_WRITE, entry);
                    }
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_CONNECTED,
                            null);
                    fireConnectionStateChanged(e);
                  } catch (IOException iox) {
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    sk.cancel();
                  }
                }

                if (readChannel != null) {
                  try {
                    readMessage(sk, readChannel, incomingAddress);
                  } catch (IOException iox) {
                    // IO exception -> channel closed remotely
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    sk.cancel();
                    readChannel.close();
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_DISCONNECTED_REMOTELY,
                            iox);
                    fireConnectionStateChanged(e);
                  }
                }
              }
            }
          } catch (NullPointerException npex) {
            // There seems to happen a NullPointerException within the select()
            npex.printStackTrace();
            logger.warn("NullPointerException within select()?");
          }
          processPending();
        }
        if (ssc != null) {
          ssc.close();
        }
      } catch (IOException iox) {
        logger.error(iox);
        lastError = iox;
      }
      if (!stop) {
        stop = true;
        synchronized (DefaultTcpTransportMapping.this) {
          server = null;
        }
      }
    }
コード例 #10
0
ファイル: Client.java プロジェクト: jinxingwang/cse461
  public static void main(String[] args) throws Exception {
    //////////////////// STAGE A//////////////////////////////////////////
    int portNum = 12235;
    //        InetAddress ip=InetAddress.getLocalHost();
    InetAddress ip = InetAddress.getByName("attu2.cs.washington.edu");

    DatagramSocket sock = new DatagramSocket();

    byte[] response = new byte[HEADER_SIZE + 16];
    String partA = "hello world\0";
    byte[] buf = createBuffer(partA.getBytes(), 0, STEP1);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, portNum);
    sock.send(packet);
    packet = new DatagramPacket(response, response.length);
    sock.receive(packet);
    int[] a2 = partA(response); // putting the 4 ints from server into int[]

    //      for (int i = 0; i < a2.length; i++) {
    //          System.out.println(a2[i]);
    //      }

    ////////////////////// STAGE B////////////////////////////////////////

    int numSent = 0;
    int send = a2[0];
    int len = a2[1];
    portNum = a2[2];
    int secretA = a2[3];
    System.out.println("The secrets:\nA: " + secretA);

    sock.setSoTimeout(500); // .5s

    while (numSent < send) {
      // create packet
      buf = createBuffer(partB(numSent, len), secretA, STEP1);
      packet = new DatagramPacket(buf, buf.length, ip, portNum);
      sock.send(packet);
      // send packet
      try {
        sock.receive(new DatagramPacket(response, response.length));
        numSent++;
        ByteBuffer temp = ByteBuffer.wrap(response);
        checkHeader(temp, 4, secretA, STEP1);
        //              System.out.println(temp.getInt());  // For debug. See if counts up by 1
      } catch (SocketTimeoutException e) {
        // if there's a timeout, try again
        continue;
      }
    }
    response = new byte[HEADER_SIZE + 8]; // 8 bytes -- 2 integers
    sock.receive(new DatagramPacket(response, response.length));
    ByteBuffer bb = ByteBuffer.wrap(response);
    // Header
    checkHeader(bb, 8, secretA, STEP2);

    // reset the port number to the one given
    portNum = bb.getInt();
    int secretB = bb.getInt();
    System.out.println("B: " + secretB);

    // close the UDP socket
    sock.close();

    /////////////////////////// STAGE C///////////////////////////////////
    Socket socket = new Socket(ip, portNum);
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    response = new byte[HEADER_SIZE + 16]; // 4 ints given to us this time
    in.read(response);
    bb = ByteBuffer.wrap(response);
    // Header
    checkHeader(bb, 13, secretB, STEP2);

    // num2 len2 secretC and char c

    numSent = bb.getInt();
    len = bb.getInt();
    int secretC = bb.getInt();
    System.out.println("C: " + secretC);

    // stage d
    byte c = (byte) bb.getChar();
    buf = new byte[len];
    Arrays.fill(buf, c);
    for (int i = 0; i < numSent; i++) {
      byte[] b = createBuffer(buf, secretC, STEP1);
      out.write(b);
    }
    response = new byte[12 + 4]; // one integer. secretD plus header
    in.read(response);
    bb = ByteBuffer.wrap(response);
    checkHeader(bb, 4, secretC, STEP2);

    int secretD = bb.getInt();
    socket.close();
    in.close();
    out.close();
    System.out.println("D: " + secretD);
  }