Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package algomidtermserver;
- import java.io.*;
- import java.net.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.util.LinkedList;
- import java.util.Random;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.*;
- public class Server extends JFrame {
- private JTextField userText;
- private JTextArea chatWindow;
- private ServerSocket server;
- private int clientNo = 0;
- int z = 0;
- boolean check[] = {false, false, false, false};
- private LinkedList<Connection> AllConnections = new LinkedList<Connection>();
- private int maxPlayers = 3;
- //constructor
- public Server() {
- super("Server");
- userText = new JTextField();
- userText.addActionListener(
- new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- String command = e.getActionCommand();
- if (command.substring(0, 4).equals("inf-")) {
- int ID = Character.getNumericValue(command.charAt(4));
- for (int i = 0; i < AllConnections.size(); i++) {
- if (ID == Integer.parseInt(AllConnections.get(i).clientID)) {
- AllConnections.get(i).tag = "1";
- break;
- }
- }
- }
- userText.setText("");
- }
- }
- );
- add(userText, BorderLayout.NORTH);
- chatWindow = new JTextArea();
- add(new JScrollPane(chatWindow));
- setSize(300, 1300);
- setVisible(true);
- }
- public void startRunning() {
- try {
- server = new ServerSocket(6789, 100);
- while (true) {
- showMessage("\nWaiting for a connection");
- Socket newConnection = server.accept();
- try {
- AllConnections.add(new Connection(newConnection));
- clientNo++;
- if (AllConnections.size() == maxPlayers) {
- System.out.println("max player reached");
- //-----------------------------------------------------------------------------------------------
- sendCommandz(1);
- try {
- Thread.sleep(10000);
- } catch (InterruptedException ex) {
- Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
- }
- System.out.println("starting to send locations");
- StartSendingLocations locationSender = new StartSendingLocations();
- sendCommandz(2);
- try {
- for (int i = 0; i < (60 * 5); i++) {
- Thread.sleep(1000);
- int zombieCounter = 0;
- for (int x = 0; x < AllConnections.size(); x++) {
- if (AllConnections.get(x).tag.equals("1")) {
- zombieCounter++;
- }
- }
- if (zombieCounter == maxPlayers) {
- sendCommandz(3);
- break;
- }
- if (i == 300 && zombieCounter != maxPlayers) {
- sendCommandz(4);
- break;
- }
- if(AllConnections.size()!= maxPlayers){
- closeAllConnection();
- break;
- }
- }
- locationSender.stopSending();
- clientNo = 0;
- } catch (InterruptedException ex) {
- Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- } catch (IOException iOException) {
- showMessage("\n Error: A client failed to connect");
- }
- }
- } catch (IOException ioException) {
- ioException.printStackTrace();
- }
- }
- private class StartSendingLocations extends Thread {
- LinkedList<String[]> AllLocations = new LinkedList<String[]>();
- StartSendingLocations() {
- start();
- }
- boolean sendingLocation = true;
- void stopSending() {
- sendingLocation = false;
- }
- @Override
- public void run() {
- do {
- showMessage("\nCLIENT - preparing locations");
- for (int i = 0; i < AllConnections.size(); i++) {
- if (AllConnections.get(i).location[0].isEmpty()) {
- continue;
- }
- AllLocations.add(new String[]{AllConnections.get(i).location[0], AllConnections.get(i).location[1],
- AllConnections.get(i).clientID, AllConnections.get(i).tag, AllConnections.get(i).nickName});
- // showMessage("\n Name: " + AllLocations.get(i)[4] + "\nlat: " + AllLocations.get(i)[0] + "\nlong: " + AllLocations.get(i)[1]);
- }
- for (int i = 0; i < AllConnections.size(); i++) {
- System.out.println("Player " + AllConnections.get(i).clientID + " - " + AllConnections.get(i).tag);
- }
- showMessage("\nCLIENT - sending location");
- showMessage("\nSize - " + AllLocations.size());
- for (int i = 0; i < AllConnections.size(); i++) {
- try {
- AllConnections.get(i).output.writeObject(AllLocations);
- AllConnections.get(i).output.flush();
- AllConnections.get(i).output.reset();
- } catch (IOException ioException) {
- chatWindow.append("\n something went wrong in sending location");
- }
- }
- AllLocations.clear();
- showMessage("\nCLIENT - location sent");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ex) {
- Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
- }
- } while (sendingLocation);
- }
- }
- private class Connection extends Thread {
- private String clientID = Integer.toString(clientNo);
- private ObjectOutputStream output;
- private ObjectInputStream input;
- private Socket clientSocket;
- private String[] location = {"", ""};
- private String nickName;
- private String tag = "0";
- //Creates a thread for the client
- Connection(Socket clientThread) throws IOException {
- clientSocket = clientThread;
- output = new ObjectOutputStream(clientThread.getOutputStream());
- output.flush();
- input = new ObjectInputStream(clientThread.getInputStream());
- showMessage("\n Stream are now setup!");
- start();
- }
- //Starts conversation
- @Override
- public void run() {
- //Get the nickname sended by client when connection established
- try {
- nickName = (String) input.readObject();
- output.writeObject(new String[]{"CLIENTID", clientID});
- } catch (IOException ex) {
- ex.printStackTrace();
- System.out.println("Cannot read nickname");
- } catch (ClassNotFoundException ex) {
- System.out.println("Client did not send a String");
- }
- showMessage("\nCLIENT " + clientID + " - has joined the server");
- do {
- try {
- //reads this clients details from the clients device
- // System.out.println("waiting Data " + clientID);
- Object objectInput = input.readObject();
- //System.out.println("data Received " + clientID);
- if (objectInput.getClass().isArray()) {
- String[] arrayInput = (String[]) objectInput;
- if (arrayInput[0].equals("INFECT")) {
- System.out.println(clientID + " INFECTING SOMEONE");
- System.out.println(AllConnections.size());
- for (int i = 0; i < AllConnections.size(); i++) {
- System.out.println("i = " + i);
- if (arrayInput[1].equals(AllConnections.get(i).clientID)) {
- System.out.println(AllConnections.get(i).clientID + " tag changed");
- AllConnections.get(i).tag = "1";
- break;
- }
- }
- } else {
- showMessage("\nCLIENT " + clientID + " - location recieved");
- location = (String[]) objectInput;
- }
- }
- } catch (ClassNotFoundException classNotFoundException) {
- showMessage("\n idk what that user send!");
- } catch (EOFException ex) {
- //Client properly closed connection
- System.out.println("Client end the connection with .close");
- break;
- } catch (SocketException ex) {
- //Client prematurely closed connection
- System.out.println("Client closed the connection not using close");
- break;
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- } while (true);
- showMessage("\nCLIENT " + clientID + " - has left the connection");
- //When chat is over. close all connections.
- try {
- output.close();
- input.close();
- clientSocket.close();
- AllConnections.remove(this);
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- }
- //updates chatWindow
- private void showMessage(final String text) {
- SwingUtilities.invokeLater(
- new Runnable() {
- public void run() {
- chatWindow.append(text);
- }
- }
- );
- }
- //Send message to all clients
- private void sendMessage(int ClientID, final String text) {
- for (int i = 0; i < AllConnections.size(); i++) {
- try {
- AllConnections.get(i).output.writeObject("CLIENT " + ClientID + " - " + text);
- AllConnections.get(i).output.flush();
- } catch (IOException ex) {
- showMessage("\nError occured in sending message");
- }
- }
- }
- private void sendCommandz(int Switch) {
- //commands
- // 1 - COUNTDOWN - starts countdown on android devices and server;
- // 2 - START - if android devices and server recieve this command, timer for the whole game (2 mins) will start;
- // 3 - END - ends the streams;
- switch (Switch) {
- case 1:
- Random randomizer = new Random();
- int zombie = randomizer.nextInt(maxPlayers);
- System.out.println("first infect: " + zombie) ;
- AllConnections.get(zombie).tag = "1";
- try {
- for (int i = 0; i < AllConnections.size(); i++) {
- AllConnections.get(i).output.writeObject("COUNTDOWN");
- AllConnections.get(i).output.flush();
- AllConnections.get(i).output.reset();
- }
- } catch (IOException IOe) {
- System.out.println("xd");
- }
- break;
- case 2:
- try {
- System.out.println("Start send");
- for (int i = 0; i < AllConnections.size(); i++) {
- AllConnections.get(i).output.writeObject("START");
- AllConnections.get(i).output.flush();
- AllConnections.get(i).output.reset();
- }
- } catch (IOException IOe) {
- System.out.println("xd");
- }
- break;
- case 3:
- try {
- System.out.println("zombies send");
- for (int i = 0; i < AllConnections.size(); i++) {
- AllConnections.get(i).output.writeObject("ZOMBIES");
- AllConnections.get(i).output.flush();
- AllConnections.get(i).output.reset();
- }
- } catch (IOException IOe) {
- System.out.println("xd");
- }
- break;
- case 4:
- try {
- System.out.println("humans send");
- for (int i = 0; i < AllConnections.size(); i++) {
- AllConnections.get(i).output.writeObject("HUMANS");
- AllConnections.get(i).output.flush();
- AllConnections.get(i).output.reset();
- }
- } catch (IOException IOe) {
- System.out.println("xd");
- }
- break;
- }
- }
- public void closeAllConnection(){
- for (int i = 0; i < AllConnections.size(); i++) {
- try {
- AllConnections.get(i).output.close();
- AllConnections.get(i).input.close();
- AllConnections.get(i).clientSocket.close();
- } catch (IOException ioException) {
- chatWindow.append("\n something went wrong in sending location");
- }
- }
- AllConnections.clear();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement