Ejemplo n.º 1
3
 void send(Scores scoreTable) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(scoreTable);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("Scores Send error!");
   }
 }
Ejemplo n.º 2
1
 void send(TimeStamp timeStamp) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(timeStamp);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("TimeStamp Send error!");
   }
 }
Ejemplo n.º 3
1
 void send(PlayersList players) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(players);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("PlayersList Send error!");
   }
 }
 private void handleKeepAlive() {
   Connection c = null;
   try {
     netCode = ois.readInt();
     c = checkConnectionNetCode();
     if (c != null && c.getState() == Connection.STATE_CONNECTED) {
       oos.writeInt(ACK_KEEP_ALIVE);
       oos.flush();
       System.out.println("->ACK_KEEP_ALIVE"); // $NON-NLS-1$
     } else {
       System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
       oos.writeInt(NOT_CONNECTED);
       oos.flush();
     }
   } catch (IOException e) {
     System.out.println("handleKeepAlive: " + e.getMessage()); // $NON-NLS-1$
     if (c != null) {
       c.setState(Connection.STATE_DISCONNECTED);
       System.out.println(
           "Connection closed with "
               + c.getRemoteAddress()
               + //$NON-NLS-1$
               ":"
               + c.getRemotePort()); // $NON-NLS-1$
     }
   }
 }
Ejemplo n.º 5
0
  // Initializes a GameClinet over port to the given host,
  // requesting to join using the given handle
  private GameClient(String host, int port, String handle) throws IOException {
    conn = new Socket(host, port);
    oos = new ObjectOutputStream(conn.getOutputStream());
    oos.flush();
    ois = new ObjectInputStream(conn.getInputStream());

    oos.writeUTF(handle);
    oos.flush();

    runReceiveThread();
  }
Ejemplo n.º 6
0
 public void initializeStreams() throws IOException {
   System.out.println("ThreadWorker# initialize start");
   writer = new ObjectOutputStream((socket.getOutputStream()));
   writer.flush();
   reader = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
   System.out.println("ThreadWorker# initialize success");
 }
Ejemplo n.º 7
0
 public static void startServer() {
   try {
     System.out.println("Starting server...");
     serverSocket = new ServerSocket(7788);
     System.out.println("Server Started... Address: " + serverSocket.getInetAddress());
     while (true) {
       socket = serverSocket.accept();
       for (int i = 0; i < 10; i++) {
         if (user[i] == null) {
           System.out.println("User " + (i + 1) + " connected from " + socket.getInetAddress());
           socket.setTcpNoDelay(false);
           out = new ObjectOutputStream(socket.getOutputStream());
           in = new ObjectInputStream(socket.getInputStream());
           out.writeInt(i);
           out.flush();
           User theUser = new User(out, in, i);
           user[i] = theUser;
           Thread thread = new Thread(user[i]);
           thread.start();
           break;
         }
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 /** Start talking to the server */
 public void start() {
   String codehost = getCodeBase().getHost();
   if (socket == null) {
     try {
       // Open the socket to the server
       socket = new Socket(codehost, port);
       // Create output stream
       out = new ObjectOutputStream(socket.getOutputStream());
       out.flush();
       // Create input stream and start background
       // thread to read data from the server
       in = new ObjectInputStream(socket.getInputStream());
       new Thread(this).start();
     } catch (Exception e) {
       // Exceptions here are unexpected, but we can't
       // really do anything (so just write it to stdout
       // in case someone cares and then ignore it)
       System.out.println("Exception! " + e.toString());
       e.printStackTrace();
       setErrorStatus(STATUS_NOCONNECT);
       socket = null;
     }
   } else {
     // Already started
   }
   if (socket != null) {
     // Make sure the right buttons are enabled
     start_button.setEnabled(false);
     stop_button.setEnabled(true);
     setStatus(STATUS_ACTIVE);
   }
 }
 private TaskObjectsExecutionResults runObject(TaskObjectsExecutionRequest obj)
     throws IOException, PDBatchTaskExecutorException {
   Object res = null;
   try {
     setAvailability(false);
     _oos.writeObject(obj);
     _oos.flush();
     res = _ois.readObject();
     setAvailability(true);
   } catch (IOException e) { // worker closed connection
     processException(e);
     throw e;
   } catch (ClassNotFoundException e) {
     processException(e);
     throw new IOException("stream has failed");
   }
   if (res instanceof TaskObjectsExecutionResults) {
     _isPrevRunSuccess = true;
     return (TaskObjectsExecutionResults) res;
   } else {
     PDBatchTaskExecutorException e =
         new PDBatchTaskExecutorException("worker failed to run tasks");
     if (_isPrevRunSuccess == false && !sameAsPrevFailedJob(obj._tasks)) {
       processException(e); // twice a loser, kick worker out
     }
     _isPrevRunSuccess = false;
     _prevFailedBatch = obj._tasks;
     throw e;
   }
 }
Ejemplo n.º 10
0
  public void run() {
    try {
      System.out.println("socked");
      sock = new Socket(ii, pp);
      oout = new ObjectOutputStream(sock.getOutputStream());
      oout.flush();

      oin = new ObjectInputStream(sock.getInputStream());
      System.out.println("read ");
      rf.setLength(0);
      do {
        System.out.println("read ");
        file f = (file) oin.readObject();
        if (f.length <= 0) break;
        write(f);
      } while (true);
      oout.close();
      oin.close();
      rf.close();
      sock.close();
      xx.ConfirmPopup("Haua file namano shesh!!!");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 private PDBTEW2Listener(PDBTExecSingleCltWrkInitSrv srv, Socket s) throws IOException {
   _srv = srv;
   _s = s;
   _ois = new ObjectInputStream(_s.getInputStream());
   _oos = new ObjectOutputStream(_s.getOutputStream());
   _oos.flush();
 }
Ejemplo n.º 12
0
 public static void main(String[] args) {
   String str;
   Socket sock = null;
   ObjectOutputStream writer = null;
   Scanner kb = new Scanner(System.in);
   try {
     sock = new Socket("127.0.0.1", 4445);
   } catch (IOException e) {
     System.out.println("Could not connect.");
     System.exit(-1);
   }
   try {
     writer = new ObjectOutputStream(sock.getOutputStream());
   } catch (IOException e) {
     System.out.println("Could not create write object.");
     System.exit(-1);
   }
   str = kb.nextLine();
   try {
     writer.writeObject(str);
     writer.flush();
   } catch (IOException e) {
     System.out.println("Could not write to buffer");
     System.exit(-1);
   }
   try {
     sock.close();
   } catch (IOException e) {
     System.out.println("Could not close connection.");
     System.exit(-1);
   }
   System.out.println("Wrote and exited successfully");
 }
Ejemplo n.º 13
0
 public void sendOutput(Object obj) {
   try {
     oos.writeObject(obj);
     oos.flush();
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
  private void handleSendCode() {
    Connection c = null;
    GeneticCode code;

    try {
      netCode = ois.readInt();
      c = checkConnectionNetCode();
      if (c != null && c.getState() == Connection.STATE_CONNECTED) {
        oos.writeInt(WAITING_CODE);
        oos.flush();
        System.out.println("->WAITING_CODE"); // $NON-NLS-1$
        code = (GeneticCode) ois.readObject();
        System.out.println("Genetic code"); // $NON-NLS-1$
        oos.writeInt(CODE_RECEIVED);
        oos.flush();
        System.out.println("->CODE_RECEIVED"); // $NON-NLS-1$
        c.getInCorridor().receiveOrganism(code);
      } else {
        System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
        oos.writeInt(NOT_CONNECTED);
        oos.flush();
      }
    } catch (IOException e) {
      System.out.println("handleSendCode: " + e.getMessage()); // $NON-NLS-1$
      if (c != null) {
        c.setState(Connection.STATE_DISCONNECTED);
        System.out.println(
            "Connection closed with "
                + c.getRemoteAddress()
                + //$NON-NLS-1$
                ":"
                + c.getRemotePort()); // $NON-NLS-1$
      }
    } catch (ClassNotFoundException e) {
      System.out.println("handleSendCode: " + e.getMessage()); // $NON-NLS-1$
      if (c != null) {
        c.setState(Connection.STATE_DISCONNECTED);
        System.out.println(
            "Connection closed with "
                + c.getRemoteAddress()
                + //$NON-NLS-1$
                ":"
                + c.getRemotePort()); // $NON-NLS-1$
      }
    }
  }
Ejemplo n.º 15
0
 void send(file x) {
   try {
     oout.writeObject(x);
     oout.flush();
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
 private void handleConnect() {
   try {
     int program_version = ois.readInt();
     port = ois.readInt();
     address = listenSocket.getInetAddress();
     netCode = ois.readInt();
     Connection c = checkConnectionNetCode();
     if (c != null) {
       oos.writeInt(ALREADY_CONNECTED);
       oos.flush();
       System.out.println("->ALREADY_CONNECTED"); // $NON-NLS-1$
     } else {
       if (isAcceptingConnections()) {
         if (connections.size() < Utils.getMAX_CONNECTIONS()) {
           if (Utils.VERSION == program_version) {
             Connection newConnection = newConnection();
             if (newConnection != null) {
               oos.writeInt(CONNECTED);
               newConnection.setState(Connection.STATE_CONNECTED);
               System.out.println("->CONNECTED"); // $NON-NLS-1$
             } else {
               oos.writeInt(ALREADY_CONNECTED);
               System.out.println("->ALREADY_CONNECTED"); // $NON-NLS-1$
             }
             oos.flush();
           } else {
             oos.writeInt(INCOMPATIBLE_PROGRAM_VERSION);
             oos.flush();
             System.out.println("->INCOMPATIBLE_PROGRAM_VERSION"); // $NON-NLS-1$
           }
         } else {
           oos.writeInt(TOO_MANY_CONNECTIONS);
           oos.flush();
           System.out.println("->TOO_MANY_CONNECTIONS"); // $NON-NLS-1$
         }
       } else {
         oos.writeInt(NOT_ACCEPTING_CONNECTIONS);
         oos.flush();
         System.out.println("->NOT_ACCEPTING_CONNECTIONS"); // $NON-NLS-1$
       }
     }
   } catch (IOException ex) {
     System.out.println(ex.getMessage());
   }
 }
Ejemplo n.º 17
0
 // send a message to the output stream
 void sendMessage(String msg) {
   try {
     out.writeObject(msg);
     out.flush();
     System.out.println("Send message: " + msg);
   } catch (IOException ioException) {
     ioException.printStackTrace();
   }
 }
Ejemplo n.º 18
0
 public void sendMessage(ObjectExchange data) throws IOException {
   synchronized (this) {
     if (writer != null && !socket.isClosed()) {
       //  data.friend_id  =   transactionId;
       writer.writeObject(data);
       writer.flush();
     }
   }
 }
 private void secondChance(RRObject obj) throws ClassNotFoundException, IOException {
   try {
     obj.runProtocol(_srv, _ois, _oos);
   } catch (PDBatchTaskExecutorException e2) {
     utils.Messenger.getInstance()
         .msg(
             "PDBTEC2ListenerThread.run(): sending NoWorkerAvailableResponse() to client...", 1);
     // e.printStackTrace();
     _oos.writeObject(new NoWorkerAvailableResponse(((TaskObjectsExecutionRequest) obj)._tasks));
     _oos.flush();
   } catch (IOException e2) {
     utils.Messenger.getInstance()
         .msg("PDBTEC2ListenerThread.run(): sending FailedReply to client...", 1);
     // e.printStackTrace();
     _oos.writeObject(new FailedReply());
     _oos.flush();
   }
 }
  void returnnull(ObjectOutputStream oos) {
    if (oos != null)
      try {
        oos.writeObject(null);
        oos.flush();
      } catch (IOException ex1) {

      }
  }
Ejemplo n.º 21
0
 // Utility methods
 // Send message to client
 private void sendMessage(String message) {
   try {
     output.writeObject("KELVIN: " + message);
     output.flush();
     showMessage("\nKELVIN: " + message);
   } catch (IOException ioException) {
     chatWindow.append("\n ERROR: CANNOT SEND MESSAGE! \n");
   }
 }
Ejemplo n.º 22
0
  // send a message to the output stream
  void SendChunk(int chunkNum) {
    try {
      // Send the chunk number that will follow
      outUp.writeObject(chunkNum + "");
      outUp.flush();

      // Send the chunk
      if (chunkNum != -1) {
        byte[] fileContents = Files.readAllBytes(availableChunks[chunkNum].toPath());
        outUp.writeObject(fileContents);
        outUp.flush();
        System.out.println("Sent chunk " + chunkNum + " to Client");
      }

    } catch (IOException ioException) {
      ioException.printStackTrace();
    }
  }
  public static int sizeInBytes(Object obj) throws IOException {
    ByteArrayOutputStream byteObject = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteObject);
    objectOutputStream.writeObject(obj);
    objectOutputStream.flush();
    objectOutputStream.close();
    byteObject.close();

    return byteObject.toByteArray().length;
  }
Ejemplo n.º 24
0
 void send(GameInfo gameInfo) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(gameInfo);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("GameInfo Send error!");
   }
 }
 /**
  * sends a message to the server, and to the other clients
  *
  * @param message: message to be sent
  */
 public void sendMessage(String message) {
   try {
     System.out.println("Sending a message..." + message);
     toChatServer.writeObject(new String(message));
     toChatServer.flush();
   } catch (IOException e) {
     System.out.println("IOException in sendMessage");
     System.err.println(e);
     System.exit(1);
   }
 }
Ejemplo n.º 26
0
  @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.");
      }
    }
  }
Ejemplo n.º 27
0
  public void mouseClicked(MouseEvent e) {
    /*can = false;
    boolean f = true;
    for (int i = 0; i < 8; i++)
    {
    	for (int j = 0; j < 8; j++)
    	if (cell[i][j] == e.getSource())
    	{
    		int judege = Clicked(cell[i][j]);
    		f = false;
    		break;
    	}
    	if (!f) break;
    }*/

    boolean flage = CheckAll();
    if (flage) {
      can = false;
      if (kind.equals("" + turn)) {
        ChessBoard cel = (ChessBoard) (e.getSource());
        int judge = Clicked(cel);
        if (judge == 1) {
          try {
            System.out.println("发送前:" + cell[3][5].taken);
            out66.writeObject("落子" + turn);
            out66.flush();
            out66.writeObject(stateList.get(stateList.size() - 1));
            out66.flush();
            out66.writeObject(takenList.get(takenList.size() - 1));
            out66.flush();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
        }
      } else {
        JOptionPane.showMessageDialog(null, "请确定您的身份,您此时不能落子");
      }
    } else CheckAtTheEnd();
  }
  private synchronized void broadcast(int i) {
    ObjectOutputStream dataOut = null;

    for (Enumeration e = clients.elements(); e.hasMoreElements(); ) {
      dataOut = (ObjectOutputStream) (e.nextElement());
      try {
        dataOut.writeInt(i);
        dataOut.flush();
      } catch (Exception x) {
        System.out.println(x.getMessage() + ": Failed to broadcast to client.");
        clients.removeElement(dataOut);
      }
    }
  }
Ejemplo n.º 29
0
  byte[] messageToBuffer(Message msg) throws Exception {
    ObjectOutputStream out;
    // BufferedOutputStream bos;

    out_stream.reset();
    // bos=new BufferedOutputStream(out_stream);
    out_stream.write(Version.version_id, 0, Version.version_id.length); // write the version
    // bos.write(Version.version_id, 0, Version.version_id.length); // write the version
    out = new ObjectOutputStream(out_stream);
    // out=new ObjectOutputStream(bos);
    msg.writeExternal(out);
    out.flush(); // needed if out buffers its output to out_stream
    return out_stream.toByteArray();
  }
Ejemplo n.º 30
0
  public void process() throws Exception {
    oout = new ObjectOutputStream(sock.getOutputStream());
    oout.flush();
    oin = new ObjectInputStream(sock.getInputStream());
    byte ary[] = new byte[1024 * 100];
    int tmp;
    int i = 0;
    do {
      tmp = getBytes(ary, i);
      if (tmp <= 0) break;
      file x = new file(i, tmp, ary);
      i += tmp;
      send(x);
    } while (true);

    oout.writeObject(new file(0, 0, ary));
    oout.flush();
    oout.close();
    oin.close();
    rf.close();
    sock.close();
    xx.ConfirmPopup("Vai file ta gesega.. Amar kam shesh");
  }