aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/main/java/models/CONSTS.java1
-rw-r--r--src/main/java/pokemon/Game.java113
-rw-r--r--src/main/java/pokemon/Server.java169
-rw-r--r--src/main/java/ui/LoginPanel.java64
-rw-r--r--src/main/java/ui/MainFrame.java92
5 files changed, 415 insertions, 24 deletions
diff --git a/src/main/java/models/CONSTS.java b/src/main/java/models/CONSTS.java
index 62fcfbd..ebee3a6 100644
--- a/src/main/java/models/CONSTS.java
+++ b/src/main/java/models/CONSTS.java
@@ -3,5 +3,6 @@ package models;
public class CONSTS {
public static final int port=5555;
public static final String rmiUrl="rmi://localhost:"+port+"/rmi";
+ public static final int socketPort=5556;
}
diff --git a/src/main/java/pokemon/Game.java b/src/main/java/pokemon/Game.java
new file mode 100644
index 0000000..fa08a1b
--- /dev/null
+++ b/src/main/java/pokemon/Game.java
@@ -0,0 +1,113 @@
+package pokemon;
+
+
+import java.io.Serializable;
+import java.nio.channels.SocketChannel;
+import java.util.ArrayList;
+
+import models.MonsterViewModel;
+
+public class Game implements Runnable, Serializable {
+
+ boolean player1Turn;
+ long player1Id;
+ long player2Id;
+ MonsterViewModel monster1;
+ MonsterViewModel monster2;
+ int currentHp1;
+ int currentHp2;
+ int shield1;
+ int shield2;
+ SocketChannel []players;
+
+ public Game() {
+ super();
+ }
+
+ @Override
+ public void run() {
+ // TODO Auto-generated method stub
+
+ }
+
+ public long getPlayer1Id() {
+ return player1Id;
+ }
+
+
+ public void setPlayer1Id(long player1Id) {
+ this.player1Id = player1Id;
+ }
+
+
+ public long getPlayer2Id() {
+ return player2Id;
+ }
+
+
+ public void setPlayer2Id(long player2Id) {
+ this.player2Id = player2Id;
+ }
+
+
+ public MonsterViewModel getMonster1() {
+ return monster1;
+ }
+
+
+ public void setMonster1(MonsterViewModel monster1) {
+ this.monster1 = monster1;
+ }
+
+
+ public MonsterViewModel getMonster2() {
+ return monster2;
+ }
+
+
+ public void setMonster2(MonsterViewModel monster2) {
+ this.monster2 = monster2;
+ }
+
+
+ public int getCurrentHp1() {
+ return currentHp1;
+ }
+
+
+ public void setCurrentHp1(int currentHp1) {
+ this.currentHp1 = currentHp1;
+ }
+
+
+ public int getCurrentHp2() {
+ return currentHp2;
+ }
+
+
+ public void setCurrentHp2(int currentHp2) {
+ this.currentHp2 = currentHp2;
+ }
+
+
+ public int getShield1() {
+ return shield1;
+ }
+
+
+ public void setShield1(int shield1) {
+ this.shield1 = shield1;
+ }
+
+
+ public int getShield2() {
+ return shield2;
+ }
+
+
+ public void setShield2(int shield2) {
+ this.shield2 = shield2;
+ }
+
+
+}
diff --git a/src/main/java/pokemon/Server.java b/src/main/java/pokemon/Server.java
index 52e9e77..a3296af 100644
--- a/src/main/java/pokemon/Server.java
+++ b/src/main/java/pokemon/Server.java
@@ -1,18 +1,34 @@
package pokemon;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
import java.rmi.Naming;
-import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+
import models.CONSTS;
+import models.User;
public class Server implements Runnable {
+ private ServerSocketChannel serverSocketChannel;
+ private Selector selector;
+ private ArrayList<Game> games;
+ HashMap<SocketChannel,Long > players = new HashMap<SocketChannel,Long>();
+ IService s;
+ ByteBuffer bb = ByteBuffer.allocate(1024);
public static void main(String[] args) {
Server server=new Server();
new Thread(server).start();
}
public Server() {
- IService s;
try {
s = new Service();
System.out.println("created registry at "+CONSTS.port);
@@ -23,21 +39,160 @@ public class Server implements Runnable {
e.printStackTrace();
}
+
+ try {
+ serverSocketChannel=ServerSocketChannel.open();
+
+ serverSocketChannel.socket().bind(new InetSocketAddress(CONSTS.socketPort));
+ serverSocketChannel.configureBlocking(false);
+ selector=Selector.open();
+ serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+
}
@Override
public void run() {
try {
- while(true) {
- Thread.sleep(500);
- System.out.println("serverTest");
+ Iterator<SelectionKey> iter;
+ SelectionKey key;
+
+ while(this.serverSocketChannel.isOpen())
+ {
+ selector.select();
+ iter = selector.selectedKeys().iterator();
+
+ while(iter.hasNext())
+ {
+ key = iter.next();
+ iter.remove();
+
+ if(key.isAcceptable())
+ acceptConnection(key);
+
+ if(key.isReadable())
+ readMessage(key);
+
+ }
}
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
+ } catch (Exception e) {
e.printStackTrace();
}
}
+ private void readMessage(SelectionKey key)throws Exception {
+ SocketChannel sc = (SocketChannel) key.channel();
+ StringBuilder sb = new StringBuilder();
+ int read=0;
+ while( (read=sc.read(bb)) > 0 )
+ {
+ bb.flip();
+ byte[] bytes = new byte[bb.limit()];
+ bb.get(bytes);
+ sb.append(new String(bytes));
+ bb.clear();
+ }
+ if(read==-1)
+ {
+ Long closedId=players.get(sc);
+ players.remove(sc);
+ System.out.println("Client dissconnected: "+closedId );
+ System.out.println("Remaining clients: "+players.size() );
+ sc.close();
+ return;
+ }
+ System.out.println(sb.toString());
+ String[] msg=sb.toString().trim().split(":");
+ if(msg[0].equals("LOGIN")) {
+ User newUser=new User();
+ newUser.setUsername(msg[1].trim());
+ newUser.setPassword(msg[2].trim());
+ String message;
+ User res=s.login(newUser);
+ if(res == null)
+ {
+ message="BADLOGIN";
+ ByteBuffer buff = ByteBuffer.wrap(message.getBytes());
+ sc.write(buff);
+ }
+ else {
+ message="ACCEPTED"+":"+res.id;
+ players.put(sc,res.id);
+ ByteBuffer buff = ByteBuffer.wrap(message.getBytes());
+ sc.write(buff);
+
+ }
+
+ }
+
+
+ }
+ private void acceptConnection(SelectionKey key) throws Exception {
+ SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
+
+ String address = (new StringBuilder( sc.socket().getInetAddress().toString() )).append(":").append( sc.socket().getPort() ).toString();
+ sc.configureBlocking(false);
+
+ System.out.println("adress "+address);
+
+ bb.clear();
+ int read = 0;
+ StringBuilder sb = new StringBuilder();
+
+ sc.configureBlocking(true);
+
+ while( (read = sc.read(bb)) > 0 )
+ {
+ bb.flip();
+ byte[] bytes = new byte[bb.limit()];
+ bb.get(bytes);
+ sb.append(new String(bytes));
+ bb.clear();
+ sc.configureBlocking(false);
+ }
+
+ String message = sb.toString();
+
+ System.out.println("message: " + message);
+
+ String []words = message.split(":");
+ System.out.println(words[0]);
+ if(words[0].trim().equals("LOGIN") == false)
+ {
+ System.out.println("Not Login : ");
+ return;
+ }
+ User newUser=new User();
+ newUser.setUsername(words[1].trim());
+ newUser.setPassword(words[2].trim());
+
+ User res=s.login(newUser);
+ if(res == null)
+ {
+ message="BADLOGIN";
+ ByteBuffer buff = ByteBuffer.wrap(message.getBytes());
+ sc.write(buff);
+ sc.register(selector, SelectionKey.OP_READ, address);
+ }
+ else {
+ message="ACCEPTED"+":"+res.id;
+ players.put(sc,res.id);
+ ByteBuffer buff = ByteBuffer.wrap(message.getBytes());
+ sc.write(buff);
+
+ sc.register(selector, SelectionKey.OP_READ, address);
+
+ }
+
+
+
+
+
+ }
}
diff --git a/src/main/java/ui/LoginPanel.java b/src/main/java/ui/LoginPanel.java
index 336d538..5ab4c0d 100644
--- a/src/main/java/ui/LoginPanel.java
+++ b/src/main/java/ui/LoginPanel.java
@@ -13,11 +13,15 @@ import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
import java.awt.event.ActionEvent;
public class LoginPanel extends JPanel {
public JTextField textFieldUsername;
public JTextField textFieldPassword;
+ public JButton btnLogIn;
+ JTextArea warningTextArea;
/**
* Create the panel.
@@ -43,27 +47,73 @@ public class LoginPanel extends JPanel {
textFieldPassword.setBounds(205, 106, 100, 20);
add(textFieldPassword);
- JTextArea warningTextArea = new JTextArea();
+ warningTextArea = new JTextArea();
+ warningTextArea.setWrapStyleWord(true);
+ warningTextArea.setLineWrap(true);
warningTextArea.setToolTipText("");
- warningTextArea.setText("fsdfsdfd fdsfsdfsd");
warningTextArea.setForeground(Color.RED);
warningTextArea.setFont(new Font("Monospaced", Font.PLAIN, 10));
warningTextArea.setEditable(false);
warningTextArea.setBackground(SystemColor.menu);
warningTextArea.setBounds(132, 134, 158, 36);
add(warningTextArea);
- JButton btnLogIn = new JButton("Log In");
+ btnLogIn = new JButton("Log In");
btnLogIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
- MainFrame topFrame=(MainFrame) SwingUtilities.getAncestorOfClass(MainFrame.class, LoginPanel.this);
- topFrame.getContentPane().removeAll();
- topFrame.add(new GamePanel(),BorderLayout.CENTER);
- SwingUtilities.updateComponentTreeUI(topFrame);
+// MainFrame topFrame=(MainFrame) SwingUtilities.getAncestorOfClass(MainFrame.class, LoginPanel.this);
+// topFrame.getContentPane().removeAll();
+// topFrame.add(new GamePanel(),BorderLayout.CENTER);
+// SwingUtilities.updateComponentTreeUI(topFrame);
+ Login();
}
});
btnLogIn.setBounds(174, 181, 81, 23);
add(btnLogIn);
}
+
+ public void Login() {
+ String username=textFieldUsername.getText();
+ String password=textFieldPassword.getText();
+ if(!(username.trim().length()>0 && password.trim().length()>0))
+ {
+ warningTextArea.setText("Morate uneti login informacije");
+ return;
+ }
+ String loginMsg="LOGIN:"+username+":"+password;
+ ByteBuffer bbLogin=ByteBuffer.wrap(loginMsg.getBytes());
+ MainFrame topFrame=(MainFrame) SwingUtilities.getAncestorOfClass(MainFrame.class, LoginPanel.this);
+ try {
+ SocketChannel client=topFrame.getClient();
+ ByteBuffer readBuffer=topFrame.getReadBuffer();
+ client.write(bbLogin);
+ client.configureBlocking(true);
+ readBuffer.clear();
+ StringBuilder sb=new StringBuilder();
+ while(client.read(readBuffer)>0) {
+ readBuffer.flip();
+ byte[] bytes = new byte[readBuffer.limit()];
+ readBuffer.get(bytes);
+ sb.append(new String(bytes));
+ readBuffer.clear();
+ client.configureBlocking(false);
+ }
+ String response[]=sb.toString().split(":");
+ if(response[0].trim().equals("ACCEPTED")) {
+ topFrame.setUserId(Long.parseLong(response[1].trim()));
+ topFrame.getContentPane().removeAll();
+ topFrame.getContentPane().add(new ChooseOpponentPanel(),BorderLayout.CENTER);
+ SwingUtilities.updateComponentTreeUI(topFrame);
+
+
+ }else {
+ System.out.println("Bad Login");
+ warningTextArea.setText("Pogresan Login");
+ }
+
+ } catch (Exception e) {
+ // TODO: handle exception
+ }
+ }
}
diff --git a/src/main/java/ui/MainFrame.java b/src/main/java/ui/MainFrame.java
index 0eac906..cfef0ba 100644
--- a/src/main/java/ui/MainFrame.java
+++ b/src/main/java/ui/MainFrame.java
@@ -5,31 +5,39 @@ import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
+
+import models.CONSTS;
+
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.Font;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
import java.awt.BorderLayout;
public class MainFrame extends JFrame implements Runnable {
- /**
- * Launch the application.
- */
+
+
+
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
-
- /**
- * Create the frame.
- */
+ public ByteBuffer readBuffer=ByteBuffer.allocate(1024);
+ public SocketChannel client;
public LoginPanel loginPanel=null;
public ChooseOpponentPanel chooseOpponentPanel=null;
GamePanel gamePanel=null;
+ public long userId=-1;
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 727, 429);
@@ -39,20 +47,84 @@ public class MainFrame extends JFrame implements Runnable {
getContentPane().setLayout(new BorderLayout(0, 0));
add(loginPanel,BorderLayout.CENTER);
setVisible(true);
+ this.addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosing(WindowEvent e)
+ {
+ System.out.println("EXITED");
+
+ try {
+ client.close();
+ Thread.sleep(500);
+ } catch (Exception e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ System.exit(EXIT_ON_CLOSE);
+ }
+
+ });
+
+ try {
+ client=SocketChannel.open(new InetSocketAddress(CONSTS.socketPort));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
new Thread(this).start();
}
@Override
public void run() {
while(true) {
try {
- Thread.sleep(500);
- System.out.println("testClient");
- } catch (InterruptedException e) {
+
+
+
+
+
+
+
+ } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
+ public SocketChannel getClient() {
+ return client;
+ }
+ public void setClient(SocketChannel client) {
+ this.client = client;
+ }
+ public LoginPanel getLoginPanel() {
+ return loginPanel;
+ }
+ public void setLoginPanel(LoginPanel loginPanel) {
+ this.loginPanel = loginPanel;
+ }
+ public ChooseOpponentPanel getChooseOpponentPanel() {
+ return chooseOpponentPanel;
+ }
+ public void setChooseOpponentPanel(ChooseOpponentPanel chooseOpponentPanel) {
+ this.chooseOpponentPanel = chooseOpponentPanel;
+ }
+ public GamePanel getGamePanel() {
+ return gamePanel;
+ }
+ public void setGamePanel(GamePanel gamePanel) {
+ this.gamePanel = gamePanel;
+ }
+ public ByteBuffer getReadBuffer() {
+ return readBuffer;
+ }
+ public void setReadBuffer(ByteBuffer readBuffer) {
+ this.readBuffer = readBuffer;
+ }
+ public long getUserId() {
+ return userId;
+ }
+ public void setUserId(long userId) {
+ this.userId = userId;
+ }
}