Exemplo n.º 1
0
  public ConnectFourServer() {
    JTextArea jtaLog = new JTextArea();

    // Create a scroll pane to hold text area
    JScrollPane scrollPane = new JScrollPane(jtaLog);

    // Add the scroll pane to the frame
    add(scrollPane, BorderLayout.CENTER);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(300, 300);
    setTitle("TicTacToeServer");
    setVisible(true);

    try {
      // Create a server socket
      ServerSocket serverSocket = new ServerSocket(8000);
      jtaLog.append(new Date() + ": Server started at socket 8000\n");

      // Number a session
      int sessionNo = 1;

      // Ready to create a session for every two players
      while (true) {
        jtaLog.append(new Date() + ": Wait for players to join session " + sessionNo + '\n');

        // Connect to player 1
        Socket player1 = serverSocket.accept();

        jtaLog.append(new Date() + ": Player 1 joined session " + sessionNo + '\n');
        jtaLog.append("Player 1's IP address" + player1.getInetAddress().getHostAddress() + '\n');

        // Notify that the player is Player 1
        new DataOutputStream(player1.getOutputStream()).writeInt(PLAYER1);

        // Connect to player 2
        Socket player2 = serverSocket.accept();

        jtaLog.append(new Date() + ": Player 2 joined session " + sessionNo + '\n');
        jtaLog.append("Player 2's IP address" + player2.getInetAddress().getHostAddress() + '\n');

        // Notify that the player is Player 2
        new DataOutputStream(player2.getOutputStream()).writeInt(PLAYER2);

        // Display this session and increment session number
        jtaLog.append(new Date() + ": Start a thread for session " + sessionNo++ + '\n');

        // Create a new thread for this session of two players
        HandleASession task = new HandleASession(player1, player2);

        // Start the new thread
        new Thread(task).start();
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
Exemplo n.º 2
0
 public static void main(String[] args) {
   boolean sender = false;
   File fi = null;
   try {
     if (args.length == 0) {
       int ret =
           JOptionPane.showConfirmDialog(
               null,
               "Are you the sender? (no = reciever)",
               "Send/Recieve",
               JOptionPane.YES_NO_OPTION);
       JFileChooser chooser = new JFileChooser();
       if (ret == JOptionPane.YES_OPTION) {
         chooser.showOpenDialog(null);
         sender = true;
       } else {
         chooser.showSaveDialog(null);
         sender = false;
       }
       fi = chooser.getSelectedFile();
     } else {
       if (args[0].equalsIgnoreCase("-s")) {
         sender = true;
       } else if (args[0].equalsIgnoreCase("-r")) {
         sender = false;
       }
       fi = new File(args[1]);
     }
   } catch (Exception e) {
     e.printStackTrace();
     exit();
   }
   if (sender && !fi.exists()) {
     System.err.println("Cannot send, file doesn't exist");
     exit();
   }
   try {
     if (sender) {
       ServerSocket ss = new ServerSocket(DEFAULT_PORT);
       Socket sck = ss.accept();
       byte[] hsh = SecureUtils.hash(fi);
       System.out.println(SecureUtils.hexify(hsh));
       sendFile(sck, fi, hsh);
       sck.close();
     } else {
       Socket sck = new Socket("localhost", DEFAULT_PORT);
       byte[] hsh = recvFile(sck, fi);
       System.out.println(SecureUtils.hexify(hsh));
       sck.close();
     }
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 3
0
 public Server(int port) {
   ServerSocket serverSocket = null;
   try {
     serverSocket = new ServerSocket(port);
     clientSocket = serverSocket.accept();
     chatField.setText("------CONNECTION ESTABLISHED------");
     out = new PrintWriter(clientSocket.getOutputStream(), true);
     in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
     enableChat();
   } catch (IOException e) {
     chatField.setText("Connection Fail");
   }
 }
Exemplo n.º 4
0
  // Cleanup for disconnect
  private static void cleanUp() {
    try {
      if (hostServer != null) {
        hostServer.close();
        hostServer = null;
      }
    } catch (IOException e) {
      hostServer = null;
    }

    try {
      if (socket != null) {
        socket.close();
        socket = null;
      }
    } catch (IOException e) {
      socket = null;
    }

    try {
      if (in != null) {
        in.close();
        in = null;
      }
    } catch (IOException e) {
      in = null;
    }

    if (out != null) {
      out.close();
      out = null;
    }
  }
Exemplo n.º 5
0
    @Override
    public void run() {

      try {
        // Create a server socket
        ServerSocket serverSocket = new ServerSocket(8000);
        textArea.append("TCP connection listener started at " + new Date() + '\n');

        while (true) {

          // Listen for a new connection request
          Socket socket = serverSocket.accept();

          // Display the client number
          textArea.append(
              "Starting thread for TCP client " + clientNo + " at " + new Date() + '\n');

          // Find the client's host name, and IP address
          InetAddress inetAddress = socket.getInetAddress();
          textArea.append(
              "Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n");
          textArea.append(
              "Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n");

          // Create a new thread for the TCP connection
          HandleTCPClient task = new HandleTCPClient(socket);

          // Start the new thread
          new Thread(task).start();

          // Increment clientNo
          clientNo++;
        }

      } catch (IOException ex) {
        System.err.println(ex);
      }
    }
Exemplo n.º 6
0
  public void run() {
    Socket socket = null;
    try {
      host = InetAddress.getLocalHost().getHostAddress();
      l.setText("Adres servera : " + host);
      serverSocket = new ServerSocket(port);
      JOptionPane.showMessageDialog(null, "Serwer dzia³a na adresie " + host);
      while (true) {
        socket = serverSocket.accept();
        if (socket != null) {
          sList.add(new ServerThread(socket, clientList, this));
        }
      }
    } catch (Exception e) {

    }
  }
Exemplo n.º 7
0
  public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(PORT);
    System.out.println("Started: " + s);
    frame.setPreferredSize(new Dimension(400, 400));
    frame.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });
    JMenuBar one = new JMenuBar();
    JMenu second = new JMenu("OPTIONS");
    //	JMenuItem third = new JMenuItem("NEW GAME");
    JMenuItem fourth = new JMenuItem("EXIT");
    fourth.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            try {
              exit(evt);
            } catch (IOException e) {
            }
          }
        });
    // second.add(third);
    second.add(fourth);
    one.add(second);
    frame.setJMenuBar(one);
    frame.setLayout(new java.awt.GridLayout(3, 3));
    button = new JButton[10];
    for (int i = 1; i < 10; i++) {
      button[i] = new JButton();
      button[i].setBackground(Color.lightGray);
      button[i].setActionCommand(Integer.toString(i));
      button[i].addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              print(evt.getActionCommand());
              try {
                func(socket, evt.getActionCommand());
                String check = win();
                finalresult(check);
                if (check != "") {
                  func(socket, check);
                } else {
                  func(socket, evt.getActionCommand());
                }
                ;
              } catch (IOException e) {
              }
            }
          });
      frame.add(button[i]);
    }

    try {
      socket = s.accept();
      frame.pack();
      frame.setVisible(true);
      try {
        System.out.println("Connection accepted: " + socket);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        /*  while(true)
        {
        String str=in.readLine();
        print2(str);
        }*/
        while (true) {
          String str = in.readLine();
          if (str.equals("exit")) {
            System.exit(0);
          }
          if (str.equals("tie")) {
            JOptionPane.showMessageDialog(null, "It is a tie between the two");
            System.exit(0);
          } else {

            if (str.equals("winserver")) {
              System.out.println("server has won");
              JOptionPane.showMessageDialog(null, "the server has won the game");
              System.exit(0);
            } else {
              if (str.equals("winclient")) {
                JOptionPane.showMessageDialog(null, "the client has won the game");
                System.exit(0);
              } else {
                System.out.println(str);
                print2(str);
              }
            }
          }
        }
      } catch (Exception e) {
      } // finally {socket.close();
      // }
    } catch (Exception e) {
    } // finally {s.close();
    // }
  }
 public void run() {
   if (isServer) {
     try {
       sSocket = new ServerSocket(portNr);
     } catch (IOException e) {
       e.printStackTrace();
     }
     while (shouldRun) {
       try {
         Socket s = sSocket.accept();
         ServerService c = new ServerService(s, gameData, this, cont);
         services.add(c);
         c.start();
         clientsJoined++;
         System.out.println(
             clientsJoined + " " + cont.getHostPlayers() + " " + cont.getGuestPlayers());
         if (clientsJoined == cont.getHostPlayers() + cont.getGuestPlayers() - 1) {
           System.out.println("ready");
           ready = true;
         }
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
     for (ServerService a : services) a.setShouldRun(false);
   } else {
     while (shouldRun) {
       try {
         String response = responseFromServer.readLine();
         if (response.startsWith("spl")) {
           spl = response.substring(3);
           serverResponse = true;
         }
         if (response.startsWith("opl")) {
           opponentResponse = true;
           opl = response.substring(3);
         }
         if (response.startsWith("gamechallenge")) serverGameData = response;
         if (response.equals("sidefull")) cs.playerNotAdded();
         if (response.equals("playeradded")) cs.playerAdded();
         if (response.startsWith("chat")) {
           parseChatMessage(response);
         }
         if (response.startsWith("water")) {
           waterResponse(response);
         }
         if (response.startsWith("hit")) {
           System.out.println("ship shot");
           hitResponse(response);
         }
         if (response.startsWith("shipSuccessfullyPlaced")) {
           shipPlacedResponse(response);
         }
         if (response.startsWith("destroyed")) {
           destroyedResponse(response);
         }
         if (response.equals("endGame")) {
           closeDown();
         }
         if (response.startsWith("allShipsDestroyed")) allShipsDestroyed(response);
         response = null;
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
Exemplo n.º 9
0
  // The main procedure
  public static void main(String args[]) {
    String s;

    initGUI();

    while (true) {
      try { // Poll every ~10 ms
        Thread.sleep(10);
      } catch (InterruptedException e) {
      }

      switch (connectionStatus) {
        case BEGIN_CONNECT:
          try {
            // Try to set up a server if host
            if (isHost) {
              hostServer = new ServerSocket(port);
              socket = hostServer.accept();
            }

            // If guest, try to connect to the server
            else {
              socket = new Socket(hostIP, port);
            }

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            changeStatusTS(CONNECTED, true);
          }
          // If error, clean up and output an error message
          catch (IOException e) {
            cleanUp();
            changeStatusTS(DISCONNECTED, false);
          }
          break;

        case CONNECTED:
          try {
            // Send data
            if (toSend.length() != 0) {
              out.print(toSend);
              out.flush();
              toSend.setLength(0);
              changeStatusTS(NULL, true);
            }

            // Receive data
            if (in.ready()) {
              s = in.readLine();
              if ((s != null) && (s.length() != 0)) {
                // Check if it is the end of a trasmission
                if (s.equals(END_CHAT_SESSION)) {
                  changeStatusTS(DISCONNECTING, true);
                }

                // Otherwise, receive what text
                else {
                  appendToChatBox("INCOMING: " + s + "\n");
                  changeStatusTS(NULL, true);
                }
              }
            }
          } catch (IOException e) {
            cleanUp();
            changeStatusTS(DISCONNECTED, false);
          }
          break;

        case DISCONNECTING:
          // Tell other chatter to disconnect as well
          out.print(END_CHAT_SESSION);
          out.flush();

          // Clean up (close all streams/sockets)
          cleanUp();
          changeStatusTS(DISCONNECTED, true);
          break;

        default:
          break; // do nothing
      }
    }
  }
Exemplo n.º 10
0
  // ------------------------------------
  // main
  // ------------------------------------
  public static void main(String argv[]) throws Exception {
    // create a Server object
    Server theServer = new Server();

    // show GUI:
    theServer.pack();
    theServer.setVisible(true);

    // get RTSP socket port from the command line
    int RTSPport = Integer.parseInt(argv[0]);

    // Initiate TCP connection with the client for the RTSP session
    ServerSocket listenSocket = new ServerSocket(RTSPport);
    theServer.RTSPsocket = listenSocket.accept();
    listenSocket.close();

    // Get Client IP address
    theServer.ClientIPAddr = theServer.RTSPsocket.getInetAddress();

    // Initiate RTSPstate
    state = INIT;

    // Set input and output stream filters:
    RTSPBufferedReader =
        new BufferedReader(new InputStreamReader(theServer.RTSPsocket.getInputStream()));
    RTSPBufferedWriter =
        new BufferedWriter(new OutputStreamWriter(theServer.RTSPsocket.getOutputStream()));

    // Wait for the SETUP message from the client
    int request_type;
    boolean done = false;
    while (!done) {
      request_type = theServer.parse_RTSP_request(); // blocking

      if (request_type == SETUP) {
        done = true;

        // update RTSP state
        state = READY;
        System.out.println("New RTSP state: READY");

        // Send response
        theServer.send_RTSP_response();

        // init the VideoStream object:
        theServer.video = new VideoStream(VideoFileName);

        // init RTP socket
        theServer.RTPsocket = new DatagramSocket();
      }
    }

    // loop to handle RTSP requests
    while (true) {
      // parse the request
      request_type = theServer.parse_RTSP_request(); // blocking

      if ((request_type == PLAY) && (state == READY)) {
        // send back response
        theServer.send_RTSP_response();
        // start timer
        theServer.timer.start();
        // update state
        state = PLAYING;
        System.out.println("New RTSP state: PLAYING");
      } else if ((request_type == PAUSE) && (state == PLAYING)) {
        // send back response
        theServer.send_RTSP_response();
        // stop timer
        theServer.timer.stop();
        // update state
        state = READY;
        System.out.println("New RTSP state: READY");
      } else if (request_type == TEARDOWN) {
        // send back response
        theServer.send_RTSP_response();
        // stop timer
        theServer.timer.stop();
        // close sockets
        theServer.RTSPsocket.close();
        theServer.RTPsocket.close();

        System.exit(0);
      }
    }
  }
Exemplo n.º 11
0
  public void buttonPressed(Button button) {
    if (button.getId() == TitleMenu.RESTART_GAME_ID) {
      clearMenus();
      TitleMenu menu = new TitleMenu(GAME_WIDTH, GAME_HEIGHT);
      addMenu(menu);

    } else if (button.getId() == TitleMenu.START_GAME_ID) {
      clearMenus();
      isMultiplayer = false;

      localId = 0;
      synchronizer = new TurnSynchronizer(this, null, 0, 1);
      synchronizer.setStarted(true);

      createLevel(TitleMenu.level);
    } else if (button.getId() == TitleMenu.SELECT_LEVEL_ID) {
      addMenu(new LevelSelect(false));
    } else if (button.getId() == TitleMenu.SELECT_HOST_LEVEL_ID) {
      addMenu(new LevelSelect(true));
    } else if (button.getId() == TitleMenu.HOST_GAME_ID) {
      addMenu(new HostingWaitMenu());
      isMultiplayer = true;
      isServer = true;
      try {
        if (isServer) {
          localId = 0;
          serverSocket = new ServerSocket(3000);
          serverSocket.setSoTimeout(1000);

          hostThread =
              new Thread() {

                public void run() {
                  boolean fail = true;
                  try {
                    while (!isInterrupted()) {
                      Socket socket = null;
                      try {
                        socket = serverSocket.accept();
                      } catch (SocketTimeoutException e) {

                      }
                      if (socket == null) {
                        System.out.println("asdf");
                        continue;
                      }
                      fail = false;

                      packetLink = new NetworkPacketLink(socket);

                      createServerState = 1;
                      break;
                    }
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                  if (fail) {
                    try {
                      serverSocket.close();
                    } catch (IOException e) {
                    }
                  }
                };
              };
          hostThread.start();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (button.getId() == TitleMenu.JOIN_GAME_ID) {
      addMenu(new JoinGameMenu());
    } else if (button.getId() == TitleMenu.CANCEL_JOIN_ID) {
      popMenu();
      if (hostThread != null) {
        hostThread.interrupt();
        hostThread = null;
      }
    } else if (button.getId() == TitleMenu.PERFORM_JOIN_ID) {
      menuStack.clear();
      isMultiplayer = true;
      isServer = false;

      try {
        localId = 1;
        packetLink = new ClientSidePacketLink(TitleMenu.ip, 3000);
        synchronizer = new TurnSynchronizer(this, packetLink, localId, 2);
        packetLink.setPacketListener(this);
      } catch (Exception e) {
        e.printStackTrace();
        // System.exit(1);
        addMenu(new TitleMenu(GAME_WIDTH, GAME_HEIGHT));
      }
    } else if (button.getId() == TitleMenu.SELECT_DIFFICULTY_ID) {
      addMenu(new DifficultySelect());
    } else if (button.getId() == TitleMenu.EXIT_GAME_ID) {
      System.exit(0);
    }
  }
Exemplo n.º 12
0
 // wait for connection, then display connection information
 public void waitForConnection() throws IOException {
   showMessage("Waiting for someone to connect... \n");
   connection = server.accept();
   showMessage("Now connected to " + connection.getInetAddress().getHostName());
 }