diff --git a/.idea/workspace (1).xml b/.idea/workspace (1).xml deleted file mode 100644 index 6b11dec..0000000 --- a/.idea/workspace (1).xml +++ /dev/null @@ -1,1050 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - DEFINITION_ORDER - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - project - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1470646840402 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1.8 - - - - - - - - \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml index e188593..800cfec 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -1,5 +1,8 @@ + + + @@ -14,6 +17,7 @@ + @@ -24,85 +28,72 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -117,11 +108,26 @@ @@ -134,8 +140,8 @@ @@ -162,7 +168,6 @@ - @@ -197,40 +202,9 @@ + @@ -243,9 +217,13 @@ - + + + + + @@ -690,7 +668,7 @@ - - @@ -745,36 +733,64 @@ - + - - + - + - - - + + + - + - - + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - file://$PROJECT_DIR$/src/console.java - 17 - - - - - + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - + - + - - - - - - - - - - - - - - - - - - - - - - + - + + - - - - - + @@ -971,214 +858,128 @@ - - + - - - + - + - - - - - - - - - - - - + - + - - - - - + - + - - - + - + - - - - - - - - - - - - + - + - - - - - + - + - - - + - + - - - - - - - - - - - - + - + - - - - - + - + - - - + - + - - - - - - - - - - - - + - + - - - - - + - + - - - + - + - - - - - - - - - - - - + - + - - - - - + @@ -1211,81 +1012,126 @@ - - - - - + + + + JAVA + socketInfo + + socketInfo + socketInfo.findSocket + + + + + + + + + + + + + socketInfo + + + Fields + Inner Classes + Constructors + Properties + Methods + + All + private - - - - - + + + + JAVA + + + com + console + netscape + oracle + org + sun + META-INF + jdk + java + javax + socketInfo.findSocket + client + socketInfo + eventNames + ctServer + javafx + eventHandler + + + + + + + Fields + Inner Classes + Constructors + Properties + Methods + + All + private - + + + + + + - - - - - - + + - + + + + + - - - - - - - + + + - + - - - - - + + + - + - - - - - + + + - + + - - - - - - - - - - - - - - + + + diff --git a/src/Protocol.java b/src/Protocol.java new file mode 100644 index 0000000..688bba1 --- /dev/null +++ b/src/Protocol.java @@ -0,0 +1,17 @@ +/** + * Created by itsmy on 11.09.2016. + */ +public class Protocol { + static class _1A{ + final static String EVENT = "EVENT"; + final static String TIME = "TIME"; + final static String AID = "AID"; + final static String PLAYLIST = "PLAYLIST"; + final static String TRACKTIME = "TRACKTIME"; + final static String DURATION = "DURATION"; + final static String AP = "AP"; + final static String PS = "PS"; + final static String ROLE = "ROLE"; + final static String ONLINE = "ONLINE"; + } +} diff --git a/src/SocketMaps.java b/src/SocketMaps.java new file mode 100644 index 0000000..e27fd20 --- /dev/null +++ b/src/SocketMaps.java @@ -0,0 +1,151 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Created by itsmy_000 on 12.09.2016. + */ +public class SocketMaps{ + public enum Events{ + CREATING, PLAY, PAUSE, REWIND, DISCONNECT + } + public enum Roles{ + CREATOR, LISTNER + } + public enum Keys{ + SOCKETID, PARTYID, EVENT, ROLE, CREATOR, CLIENT + } + private static Map SID; + private static Map PID; + private static Map EID; + private static Map info; + private static Map role; + private static Map creator; // 1 - SID, 2 - PID + private static Integer counter; + + static void initMaps(){ + counter = 0; + SID = new HashMap<>(); + PID = new HashMap<>(); + EID = new HashMap<>(); + info = new HashMap<>(); + role = new HashMap<>(); + creator = new HashMap<>(); + } + + static Integer addClient(Client c, Client.Info i){ + SID.put(counter, c); + info.put(counter, i); + PID.put(counter,null); + EID.put(counter,Events.CREATING); + return counter++; + } + + static void removeClient(Integer socketid) throws ctException{ + containSID(socketid); + Integer partyid = getPID(socketid); + if(getCreator(partyid) == socketid){ + creator.remove(partyid); + } + SID.remove(socketid); + PID.remove(socketid); + EID.remove(socketid); + role.remove(socketid); + info.remove(socketid); + } + + static void setPID(Integer socketid, Integer partyid) throws ctException{ + containSID(socketid); + PID.put(socketid,partyid); + } + + static void setEID(Integer socketid, Events event) throws ctException { + containSID(socketid); + EID.put(socketid, event); + } + + static void setRole(Integer socketid, Roles r) throws ctException { + containSID(socketid); + role.put(socketid, r); + } + + static void setCreator(Integer partyid, Integer creatorsid){ + if(!creator.containsKey(partyid)) { + creator.put(partyid,creatorsid); + + } + } + + static Client getClient(Integer socketid) throws ctException{ + containSID(socketid); + return SID.get(socketid); + } + + static Client.Info getInfo(Integer socketid) throws ctException{ + containSID(socketid); + return info.get(socketid); + } + + static Integer getPID(Integer socketid) throws ctException { + containSID(socketid); + return PID.get(socketid); + } + + static Roles getRole(Integer socketid) throws ctException { + containSID(socketid); + return role.get(socketid); + } + + static Events getEID(Integer socketid) throws ctException { + containSID(socketid); + return EID.get(socketid); + } + + static ArrayList getAllClients(){ + ArrayList list = new ArrayList<>(); + for (Integer integer : SID.keySet()) { + list.add(integer); + } + return list; + } + + static ArrayList getAllParty(Integer partyid){ + ArrayList list = new ArrayList<>(); + Console.debug("Enter to getAllParty()"); + for (int i = 0; i < PID.size(); i++) { + Map.Entry temp = PID.entrySet().iterator().next(); + if(temp.getValue() == partyid) { + list.add(temp.getKey()); + Console.debug("getAllParty()|"+temp.getKey()+"|"+temp.getValue()); + } + } + return list; + } + + static Integer getCreator(Integer partyid){ + int noCreator = 0; + try{ + containPID(partyid); + return creator.get(partyid); + } + catch (ctException temp){ + temp = null; + return noCreator; + } + } + + private static void containSID(Integer socketid) throws ctException{ + if(!SID.containsKey(socketid)){ + throw new ctException("Not finded SID Key!"); + } + } + + private static void containPID(Integer partyid) throws ctException{ + if(!PID.containsKey(partyid)){ + throw new ctException("Not finded PID Key!"); + } + } + +} + diff --git a/src/client.java b/src/client.java index 716286c..2701119 100644 --- a/src/client.java +++ b/src/client.java @@ -1,43 +1,71 @@ import javax.json.Json; import javax.json.stream.JsonParser; +import javax.json.stream.JsonParsingException; import javax.xml.bind.DatatypeConverter; import java.io.*; +import java.math.BigDecimal; import java.net.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.NoSuchElementException; import java.util.Scanner; +import java.util.concurrent.Exchanger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by itsmy on 08.08.2016. */ -public class client extends Thread { +public class Client extends Thread { + public class Info{ + Integer VKID,DURATION; + String PLAYLIST,PROTOCOL,AUDIOID; + BigDecimal TIME, TRACKTIME; + Boolean AP; + private void initInstance(){ + VKID = 0; + DURATION = 0; + PLAYLIST = ""; + PROTOCOL = ""; + AUDIOID = ""; + TIME = BigDecimal.ZERO; + TRACKTIME = BigDecimal.ZERO; + AP = false; + } + } private Socket socket; private OutputStream out; private InputStream in; private Integer socketid; - private Boolean isClosing = false; + private Boolean _instanceClosed = false; +// private Boolean isClosing = false; - public void openSocket(Socket s) throws IOException { + public void initSocket(Socket s) throws IOException { socket = s; out = socket.getOutputStream(); in = socket.getInputStream(); - socketid = socketInfo.getNewID(); - console.debug("Create new socket " + socketid); - socketInfo.create(this, socketid); + socketid = SocketMaps.addClient(this, new Info()); + try { + SocketMaps.getInfo(socketid).initInstance(); + } + catch (ctException e){ + Console.socket(socketid,"Try to close!"); + } + Console.debug("Create new socket " + socketid); start(); } public void run() { - console.socket(socketid, "New connection"); - wsControl(); + Console.socket(socketid, "New connection"); + runSocket(); } - public void close() { - if(!socketInfo.isOnline(socketid)){ + public void closeSocket(){ + if(!_instanceClosed){ + _instanceClosed = true; + } + else{ return; } try { @@ -46,46 +74,52 @@ public class client extends Thread { socket.close(); } catch (IOException e) { } - console.socket(socketid, "Disconnected"); - socketInfo.close(socketid); + try { + SocketMaps.removeClient(socketid); + SocketMaps.removeClient(socketid); + Console.socket(socketid, "Disconnected"); + }catch (ctException e){ + Console.socket(socketid,e.toString()); + } } - public void wsControl() { - handshake(); - if (!socketInfo.isHttpAuth(socketid)) { - return; - } - String msg = readSocket(); - parseInput(msg); - if(!socketInfo.isProtocolAuth(socketid)){socketInfo.checkProtocol(socketid);} - if(!socketInfo.isProtocolAuth(socketid)){close(); return;} - eventHandler.connect(socketid); - while (socketInfo.isOnline(socketid)) { - msg = readSocket(); - parseInput(msg); - eventExecute(); + void checkProtocol(Integer socketid, String msg) throws ctException{ + if(SocketMaps.getInfo(socketid).PROTOCOL.equals("1A")){ + + }else{ + throw new ctException("Protocol verify failed!"); } } - public void eventExecute(){ - int id = socketInfo.findSocket.bySID(socketid); - if(id == -1){return;} - switch (socketInfo.EVENT.get(id)){ - case "play": eventHandler.play(socketid); - break; - case "pause": eventHandler.pause(socketid); - break; - case "next": eventHandler.next(socketid); - break; - case "prev": eventHandler.prev(socketid); - break; - case "wind": eventHandler.wind(socketid); - break; + public void runSocket(){ + try { + handshake(); + String msg = readSocket(); + parseInput(msg); + checkProtocol(socketid, msg); + SocketMaps.setRole(socketid, SocketMaps.Roles.LISTNER); + EventHandler.connect(socketid, SocketMaps.getPID(socketid)); + while (!_instanceClosed) { + msg = readSocket(); + parseInput(msg); + switch (SocketMaps.getRole(socketid)){ + case CREATOR: + EventHandler.sendParty(socketid); + break; + case LISTNER: + break; + } + } + }catch (ctException e){ + closeSocket(); + e.printStackTrace(); + }catch (Exception e){ + e.printStackTrace(); } - } - private String bytesToStringUTFCustom(int[] ints) { + + private String bytesToString(int[] ints) { //TODO: добавить поддержку русского языка char[] buffer = new char[ints.length]; for (int i = 0; i < buffer.length; i++) { @@ -95,57 +129,51 @@ public class client extends Thread { return new String(buffer); } - private void handshake() { - if(!socketInfo.isOnline(socketid)){close(); return;} + private void handshake() throws ctException { try { - if (!socketInfo.isHttpAuth(socketid)) { - socket.setSoTimeout(2000); - String data = new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next(); - Matcher get = Pattern.compile("^GET").matcher(data); - if (get.find()) { - Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data); - match.find(); - try { - byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" - + "Connection: Upgrade\r\n" - + "Upgrade: websocket\r\n" - + "Sec-WebSocket-Accept: " - + DatatypeConverter - .printBase64Binary( - MessageDigest - .getInstance("SHA-1") - .digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") - .getBytes("UTF-8"))) - + "\r\n\r\n") - .getBytes("UTF-8"); - out.write(response, 0, response.length); - } catch (IOException | NoSuchAlgorithmException e) { - console.out("Server Error:", e.toString()); - } - socket.setSoTimeout(0); - socketInfo.setHttpAuth(socketid, true); - console.socket(socketid, "Handshake accepted!"); + socket.setSoTimeout(2000); + String data = new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next(); + Matcher get = Pattern.compile("^GET").matcher(data); + if (get.find()) { + Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data); + match.find(); + try { + byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + + "Connection: Upgrade\r\n" + + "Upgrade: websocket\r\n" + + "Sec-WebSocket-Accept: " + + DatatypeConverter + .printBase64Binary( + MessageDigest + .getInstance("SHA-1") + .digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") + .getBytes("UTF-8"))) + + "\r\n\r\n") + .getBytes("UTF-8"); + out.write(response, 0, response.length); + } catch (IOException | NoSuchAlgorithmException e) { + Console.out("Server Error:", e.toString()); } + socket.setSoTimeout(0); + Console.socket(socketid, "Handshake accepted!"); } } catch (SocketException ignored) { } catch (NoSuchElementException e) { - console.socket(socketid, "Handshake Timeout (2000ms)"); - socketInfo.setHttpAuth(socketid, false); - close(); + Console.socket(socketid, "Handshake Timeout (2000ms)"); + closeSocket(); } catch(IllegalStateException e){ - console.socket(socketid, "Bad handshake request!"); - close(); + Console.socket(socketid, "Bad handshake request!"); + closeSocket(); } } - public Boolean sendSocket(String message) { - if(!socketInfo.isOnline(socketid)){close(); return false;} + public Boolean writeSocket(String message) { byte[] response; byte[] r; try { response = message.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { - console.socket(socketid, "Unsupported encoding!"); + Console.socket(socketid, "Unsupported encoding!"); return false; } catch (NullPointerException e) { return false; @@ -176,21 +204,20 @@ public class client extends Thread { r[8] = (byte) (response.length >>> 8); r[9] = (byte) (response.length); } else { - console.out("Socket Exception", "Too long message for sending! (>64bit)"); + Console.out("Socket Exception", "Too long message for sending! (>64bit)"); return false; } try { out.write(r, 0, r.length); return true; } catch (IOException e) { - console.out("Socket Exeption", "Client socket is closed?! Closing socket connection!"); - close(); + Console.out("Socket Exeption", "Client socket is closed?! Closing socket connection!"); + closeSocket(); return false; } } public String readSocket() { - if(!socketInfo.isOnline(socketid)){close(); return null;} String out = ""; try { int[] MSG = new int[0]; @@ -200,10 +227,10 @@ public class client extends Thread { int OPCODE = in.read(); //читаем OPCODE byte switch (OPCODE) { case -1: - close(); //закрываем чтение потока при -1 + closeSocket(); //закрываем чтение потока при -1 return null; case 136: - close(); + closeSocket(); return null; case 129: LENGTH = in.read(); //читаем второй бит с данными о размере сообщения @@ -246,23 +273,22 @@ public class client extends Thread { MSG[j] = (byte) (enc ^ KEY[j & 0x3]); } if (MSG.length > 0) { - out = bytesToStringUTFCustom(MSG); + out = bytesToString(MSG); } else { return null; } } } catch (IOException e) { - console.out("Socket Exception", "Client socket is closed?! Closing socket connection!"); - close(); + Console.out("Socket Exception", "Client socket is closed?! Closing socket connection!"); + closeSocket(); } - if(!socketInfo.isOnline(socketid)){close(); return null;} - console.socket(socketid, "Получаю: " + out); + Console.socket(socketid, "Получаю: " + out); return out; } - public Boolean parseInput(String input) { - if(!socketInfo.isOnline(socketid)){close();return false;} + public Boolean parseInput(String input) throws ctException{ try { + Info inf = SocketMaps.getInfo(socketid); String keyName = null; JsonParser jsonParser = Json.createParser(new StringReader(input)); while (jsonParser.hasNext()) { @@ -272,30 +298,86 @@ public class client extends Thread { keyName = jsonParser.getString(); break; case VALUE_STRING: - socketInfo.setString(socketid, keyName, jsonParser.getString()); + setString(socketid, keyName, jsonParser.getString(), inf); break; case VALUE_NUMBER: - socketInfo.setInteger(socketid, keyName, jsonParser.getBigDecimal()); + setInteger(socketid, keyName, jsonParser.getBigDecimal(), inf); break; case VALUE_FALSE: - socketInfo.setBoolean(socketid, keyName, false); + setBoolean(socketid, keyName, false, inf); break; case VALUE_TRUE: - socketInfo.setBoolean(socketid, keyName, true); + setBoolean(socketid, keyName, true, inf); break; case VALUE_NULL: - // don't set anything break; default: - // we are not looking for other events break; } } return true; }catch(NullPointerException e){ - console.socket(socketid,"Request parsing error!"); - return false; - } + Console.socket(socketid,"Request parsing error!"); + return false; + }catch(JsonParsingException e){ + Console.socket(socketid, "JSON Parsing Error!"); + return false; + } + } + + public static void setString(Integer sid, String keyName, String value, Info inf) throws ctException { + switch (keyName) { + case "EVENT": + switch (value){ + case "play": + SocketMaps.setEID(sid, SocketMaps.Events.PLAY); + break; + case "pause": + SocketMaps.setEID(sid, SocketMaps.Events.PAUSE); + break; + case "rewind": + SocketMaps.setEID(sid, SocketMaps.Events.REWIND); + break; + case "DISCONNECT": + SocketMaps.setEID(sid, SocketMaps.Events.DISCONNECT); + } + break; + case "AID": + inf.AUDIOID = value; + break; + case "PROTOCOL": + inf.PROTOCOL = value; + break; + case "PLAYLIST": + inf.PLAYLIST = value; + break; + } } + + public static void setInteger(Integer sid, String keyName, BigDecimal value, Info inf) + throws ctException{ + switch (keyName){ + case "USERID": inf.VKID = value.intValueExact(); + break; + case "TIME": inf.TIME = value; + break; + case "TRACKTIME": inf.TRACKTIME = value; + break; + case "PARTYID": SocketMaps.setPID(sid, value.intValueExact()); + break; + case "DURATION": inf.DURATION = value.intValueExact(); + break; + } + } + + public static void setBoolean(Integer sid, String keyName, Boolean value, Info inf){ + switch (keyName) { + case "AP": + inf.AP = value.booleanValue(); + break; + } + + } + } diff --git a/src/console.java b/src/console.java index c294ca5..3110028 100644 --- a/src/console.java +++ b/src/console.java @@ -1,6 +1,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.net.Socket; import java.time.Clock; import java.util.ArrayList; import java.util.regex.Pattern; @@ -8,7 +9,7 @@ import java.util.regex.Pattern; /** * Created by itsmy on 08.08.2016. */ -public class console extends Thread{ +public class Console extends Thread{ private BufferedReader in; private String line; @@ -52,7 +53,7 @@ public class console extends Thread{ } public void run() { - console.out("Server", "Welcome to the ctServer/build25"); + Console.out("Server", "Welcome to the CtServer[BUILD 030]"); while (line.equalsIgnoreCase("/stop") == false) { try{ line = in.readLine(); @@ -80,109 +81,103 @@ public class console extends Thread{ case "/restart": cRestart(); break; - default: console.out("Server","Введите /help для помощи"); + default: Console.out("Server","Введите /help для помощи"); } }catch (IOException e){ - console.out("Console","Something goes wrong..."); + Console.out("Console","Something goes wrong..."); }catch (NumberFormatException e){ - console.out("Console","Hey guy, don't be so crazy!!!"); + Console.out("Console","Hey guy, don't be so crazy!!!"); + }catch (ctException e){ } } - for (int i = 0; i < socketInfo.SOCKETID.size(); i++) { - socketInfo.CLIENT.get(i).close(); - } } private void cHide() { if(!hide){hide = true;} else {hide = false;} } - private void cList() { + private void cList() throws ctException { Integer sid; - console.out("Server","/list"); - for(int i = 0; socketInfo.SOCKETID.size() > i; i++){ - sid = socketInfo.SOCKETID.get(i); - if(socketInfo.protocolAuth.get(i)) { - console.socket(sid,"VKID " + socketInfo.VKID.get(i) - + " PROTOCOL " + socketInfo.PROTOCOL.get(i) - + " EVENT " + socketInfo.EVENT.get(i) - + " PARTYID " + socketInfo.PARTYID.get(i) - + " TIME " + socketInfo.TIME.get(i) - + " TRACKDURATION " + socketInfo.DURATION.get(i)); + Console.out("Server","/list"); + for(int i = 0; SocketMaps.getAllClients().size() > i; i++){ + sid = SocketMaps.getAllClients().get(i); + if(SocketMaps.getInfo(sid).PROTOCOL == "1A") { + Console.socket(sid,"VKID " + SocketMaps.getInfo(sid).VKID + + " PROTOCOL " + SocketMaps.getInfo(sid).PROTOCOL + + " EVENT " + SocketMaps.getEID(sid) + + " PARTYID " + SocketMaps.getPID(sid) + + " TIME " + SocketMaps.getInfo(sid).TIME + + " TRACKDURATION " + SocketMaps.getInfo(sid).DURATION); }else{ - console.socket(sid,"Protocol not checked!"); + Console.socket(sid,"Protocol not checked!"); } } } - private void cKick(String[] sx) { + private void cKick(String[] sx) throws ctException{ Integer sid; sid = Integer.valueOf(sx[1]); - if(socketInfo.findSocket.bySID(Integer.valueOf(sx[1])) != -1){ - socketInfo.getClient(sid).close(); - } + SocketMaps.getClient(sid).closeSocket(); } - private void cSend(String[] sx) { + private void cSend(String[] sx) throws ctException { Integer sid; - sid = socketInfo.findSocket.bySID(Integer.valueOf(sx[1])); - if(sid != -1){ - String msg = ""; - for (int i = 2; i < sx.length ; i++) { - msg += " "; - msg += sx[i]; - } - socketInfo.getClient(Integer.valueOf(sx[1])).sendSocket(msg); + sid = Integer.valueOf(sx[1]); + String msg = ""; + for (int i = 2; i < sx.length ; i++) { + msg += " "; + msg += sx[i]; } + SocketMaps.getClient(sid).writeSocket(msg); } private void cHelp() { - console.out("Server","/kick [socketid] для отключения сокета от сервера"); - console.out("Server","/list для отображения всех клиентов"); - console.out("Server","/info pid/sid [id] для отображения полной информации о данном клиенте"); - console.out("Server","/send [socketid] [msg] отладочная команда"); - console.out("Server","ctServer Proto Defend Development 2016"); + Console.out("Server","/kick [socketid] для отключения сокета от сервера"); + Console.out("Server","/list для отображения всех клиентов"); + Console.out("Server","/info pid/sid [id] для отображения полной информации о данном клиенте"); + Console.out("Server","/send [socketid] [msg] отладочная команда"); + Console.out("Server","CtServer Proto Defend Development 2016"); } - private void cInfo(String[] sx) { + private void cInfo(String[] sx) throws ctException { Integer sid; - Integer id; if(sx.length < 3){ - console.out("Server","/info [pid/sid] "); + Console.out("Server","/info [pid/sid] "); } else { switch (sx[1]) { case "sid": sid = Integer.valueOf(sx[2]); - id = socketInfo.findSocket.bySID(sid); - if(id == -1){break;} - console.socket(sid,"VKID " + socketInfo.VKID.get(id) - + " PROTOCOL " + socketInfo.PROTOCOL.get(id) - + " EVENT " + socketInfo.EVENT.get(id) - + " PARTYID " + socketInfo.PARTYID.get(id) - + " TRACKDURATION " + socketInfo.DURATION.get(id)); + Console.socket(sid,"VKID " + SocketMaps.getInfo(sid).VKID + + " PROTOCOL " + SocketMaps.getInfo(sid).PROTOCOL + + " EVENT " + SocketMaps.getEID(sid) + + " PARTYID " + SocketMaps.getPID(sid) + + " TRACKDURATION " + SocketMaps.getInfo(sid).DURATION); break; case "pid": - ArrayList a = socketInfo.findSocket.byPID(Integer.valueOf(sx[2])); + Integer pid = Integer.valueOf(sx[2]); + ArrayList a = SocketMaps.getAllParty(pid); for (int i = 0; i < a.size(); i++) { - id = a.get(i); - console.socket(socketInfo.SOCKETID.get(id),"VKID " + socketInfo.VKID.get(id) - + " PROTOCOL " + socketInfo.PROTOCOL.get(id) - + " EVENT " + socketInfo.EVENT.get(id) - + " PARTYID " + socketInfo.PARTYID.get(id) - + " TRACKDURATION " + socketInfo.DURATION.get(id)); + Console.socket(a.get(i),"VKID " + SocketMaps.getInfo(a.get(i)).VKID + + " PROTOCOL " + SocketMaps.getInfo(a.get(i)).PROTOCOL + + " EVENT " + SocketMaps.getEID(a.get(i)) + + " PARTYID " + SocketMaps.getPID(a.get(i)) + + " TRACKDURATION " + SocketMaps.getInfo(a.get(i)).DURATION); } break; default: - console.out("Server", "/info [pid/sid] "); + Console.out("Server", "/info [pid/sid] "); break; } } } private void cRestart(){ - for (int i = 0; i < socketInfo.SOCKETID.size(); i++) { - socketInfo.CLIENT.get(i).sendSocket("{\"EVENT\":\"RESTART\"}"); + ArrayList TempList= SocketMaps.getAllClients(); + for (int i = 0; i < TempList.size(); i++) { + try{ + SocketMaps.getClient(TempList.get(i)).writeSocket("{\"EVENT\":\"RESTART\"}"); + }catch (ctException ct){} } System.exit(99); } diff --git a/src/ctException.java b/src/ctException.java new file mode 100644 index 0000000..7ec2fcd --- /dev/null +++ b/src/ctException.java @@ -0,0 +1,8 @@ +/** + * Created by itsmy_000 on 12.09.2016. + */ +class ctException extends Exception { + ctException(String message) { + super(message); + } +} diff --git a/src/ctServer.java b/src/ctServer.java index 5455e8e..564640a 100644 --- a/src/ctServer.java +++ b/src/ctServer.java @@ -1,29 +1,29 @@ import java.net.*; import java.io.*; -public class ctServer { +public class CtServer { public static void main(String[] args) throws IOException{ - socketInfo.init(); + SocketMaps.initMaps(); try{ - new console().consoleListner(); + new Console().consoleListner(); } catch (IOException ignored){} int port = 80; - console.out("Socket Port", port+""); - ServerSocket ss = new ServerSocket(port); + Console.out("Socket Port", port+""); + ServerSocket instance = new ServerSocket(port); try { - console.out("Server", "Waiting for a client"); + Console.out("Server", "Waiting for a Client"); while(true) { - Socket socket = ss.accept(); + Socket socket = instance.accept(); try { - new client().openSocket(socket); + new Client().initSocket(socket); } catch (IOException e) { socket.close(); } } } finally { - ss.close(); + instance.close(); } } diff --git a/src/eventHandler.java b/src/eventHandler.java index 2dd03a0..97702e9 100644 --- a/src/eventHandler.java +++ b/src/eventHandler.java @@ -1,159 +1,96 @@ -import jdk.nashorn.internal.parser.JSONParser; - import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; +import java.net.Socket; import java.util.ArrayList; /** * Created by itsmy on 15.08.2016. */ -public class eventHandler { - - //TODO: переписать почти весь код здесь - //Нужно покончить с этим быдланством - public static synchronized void connect(Integer sid){ - JsonObjectBuilder creator = Json.createObjectBuilder(); - creator.add("EVENT","SERVICE"); - int id = socketInfo.findSocket.bySID(sid); - if(id == -1){return;} - ArrayList a = socketInfo.findSocket.byPID(socketInfo.PARTYID.get(id)); - if(a.size() == 1) { //Если клиент первым подключился, то он управляет +public class EventHandler { + /*TODO: разделить метод на несколько методов + * Метод записи ролей + * Метод сборки JSON + * Метод рассылки по клиентам + */ + public static synchronized void connect(Integer socketid, Integer partyid) throws ctException{ + ArrayList a = SocketMaps.getAllParty(partyid); + if(a.size() == 1) { + //Если клиент первым подключился, то он управляет + SocketMaps.setCreator(partyid, socketid); + SocketMaps.setRole(socketid, SocketMaps.Roles.CREATOR); + JsonObjectBuilder creator = Json.createObjectBuilder(); + creator.add("EVENT","SERVICE"); creator.add("ROLE", 0); creator.add("ONLINE", 0); - socketInfo.ROLE.set(id, 0); JsonObject cc = creator.build(); - socketInfo.CLIENT.get(id).sendSocket(cc.toString()); - } else if(a.size() > 1) { //Если клиент уже не первый, то всем остальным клиентам идет рассылка о новом подключении - socketInfo.ROLE.set(id, 1); + SocketMaps.getClient(socketid).writeSocket(cc.toString()); + } else if(a.size() > 1) { + //Если клиент уже не первый, то всем остальным клиентам идет рассылка о новом подключении + SocketMaps.setRole(socketid, SocketMaps.Roles.LISTNER); + JsonObjectBuilder creator = Json.createObjectBuilder(); creator.add("ONLINE" , a.size()-1); for (int i = 0; i < a.size(); i++) { - if(socketInfo.ROLE.get(i) == 0){ - JsonObject cc = creator.build(); - socketInfo.CLIENT.get(a.get(i)).sendSocket(cc.toString()); - } - else{ - JsonObjectBuilder listner = Json.createObjectBuilder(); - listner.add("EVENT","SERVICE"); - listner.add("ROLE", 1); - listner.add("ONLINE" , a.size()-1); - JsonObject lc = listner.build(); - socketInfo.CLIENT.get(a.get(i)).sendSocket(lc.toString()); + switch (SocketMaps.getRole(a.get(i))) { + case CREATOR: + JsonObject cc = creator.build(); + SocketMaps.getClient(a.get(i)).writeSocket(cc.toString()); + break; + case LISTNER: + JsonObjectBuilder listner = Json.createObjectBuilder(); + listner.add("EVENT", "SERVICE"); + listner.add("ROLE", 1); + listner.add("ONLINE", a.size() - 1); + JsonObject lc = listner.build(); + SocketMaps.getClient(a.get(i)).writeSocket(lc.toString()); + break; } } - socketInfo.CLIENT.get(id).eventExecute(); } } - public static void close(Integer sid){ - JsonObjectBuilder c = Json.createObjectBuilder(); - c.add("EVENT","SERVICE"); - int id = socketInfo.findSocket.bySID(sid); - ArrayList a = socketInfo.findSocket.byPID(socketInfo.PARTYID.get(id)); - if(a.size() < 2){return;} - if(socketInfo.ROLE.get(id) == 0){ - for (int i = 0; i < socketInfo.ROLE.size() ; i++) { - if(id != i){ - socketInfo.ROLE.set(i, 0); - JsonObjectBuilder creator = Json.createObjectBuilder(); - creator.add("EVENT","SERVICE"); - creator.add("ROLE", 1); - creator.add("ONLINE" , a.size()-2); - JsonObject lc = creator.build(); - socketInfo.CLIENT.get(i).sendSocket(lc.toString()); - break; - } - } - } - for (int i = 0; i < a.size(); i++) { -// JsonObjectBuilder listner = Json.createObjectBuilder(); -// listner.add("EVENT","SERVICE"); -// listner.add("ROLE", 1); -// listner.add("ONLINE" , a.size()-1); -// JsonObject lc = listner.build(); -// socketInfo.CLIENT.get(i).sendSocket(lc.toString()); - } - } - public static void play(Integer sid){ - int id = socketInfo.findSocket.bySID(sid); - if(id == -1){return;} - JsonObjectBuilder creator = Json.createObjectBuilder(); - creator.add("EVENT", "play"); - creator.add("tm",socketInfo.TIME.get(id)); - creator.add("tI", socketInfo.TRACKID.get(id)); - creator.add("li", "main"); - creator.add("tT", socketInfo.TRACKTIME.get(id)); - creator.add("tD", socketInfo.DURATION.get(id)); - creator.add("aP", socketInfo.AUTOPLAY.get(id)); - eventSender(id,creator); - } - public static void next(Integer sid){ - int id = socketInfo.findSocket.bySID(sid); - if(id == -1){return;} - JsonObjectBuilder creator = Json.createObjectBuilder(); - creator.add("EVENT", "next"); - creator.add("tm",socketInfo.TIME.get(id)); - creator.add("tI", socketInfo.TRACKID.get(id)); - creator.add("li", "main"); - creator.add("tT", socketInfo.TRACKTIME.get(id)); - creator.add("tD", socketInfo.DURATION.get(id)); - creator.add("aP", socketInfo.AUTOPLAY.get(id)); - eventSender(id,creator); - } - public static void prev(Integer sid){ - int id = socketInfo.findSocket.bySID(sid); - if(id == -1){return;} + public static JsonObject buildEvent(Integer socketid) throws ctException{ JsonObjectBuilder creator = Json.createObjectBuilder(); - creator.add("EVENT", "prev"); - creator.add("tm",socketInfo.TIME.get(id)); - creator.add("tI", socketInfo.TRACKID.get(id)); - creator.add("li", "main"); - creator.add("tT", socketInfo.TRACKTIME.get(id)); - creator.add("tD", socketInfo.DURATION.get(id)); - creator.add("aP", socketInfo.AUTOPLAY.get(id)); - eventSender(id,creator); + Integer pid = SocketMaps.getPID(socketid); + switch (SocketMaps.getEID(SocketMaps.getCreator(pid))){ + case PLAY: creator.add("EVENT", "play"); + break; + case PAUSE: creator.add("EVENT", "pause"); + break; + case REWIND: creator.add("EVENT", "rewind"); + break; + case DISCONNECT: SocketMaps.getClient(socketid).closeSocket(); + return null; + } + creator.add(Protocol._1A.TIME, SocketMaps.getInfo(socketid).TIME); + creator.add(Protocol._1A.AID, SocketMaps.getInfo(socketid).AUDIOID); + creator.add(Protocol._1A.TRACKTIME, SocketMaps.getInfo(socketid).TRACKTIME); + creator.add(Protocol._1A.DURATION, SocketMaps.getInfo(socketid).DURATION); + creator.add(Protocol._1A.PLAYLIST, SocketMaps.getInfo(socketid).PLAYLIST); + creator.add(Protocol._1A.AP, SocketMaps.getInfo(socketid).AP); + JsonObject main = creator.build(); + return main; } - public static void pause(Integer sid){ - int id = socketInfo.findSocket.bySID(sid); - if(id == -1){return;} - JsonObjectBuilder creator = Json.createObjectBuilder(); - creator.add("EVENT", "pause"); - creator.add("tm",socketInfo.TIME.get(id)); - creator.add("tI", socketInfo.TRACKID.get(id)); - creator.add("li", "main"); - creator.add("tT", socketInfo.TRACKTIME.get(id)); - creator.add("tD", socketInfo.DURATION.get(id)); - creator.add("aP", socketInfo.AUTOPLAY.get(id)); - eventSender(id,creator); + public static void sendClient(Integer socketid) throws ctException{ + JsonObject main = buildEvent(socketid); + SocketMaps.getClient(socketid).writeSocket(main.toString()); } - public static void eventSender(Integer id, JsonObjectBuilder creator){ - ArrayList a = socketInfo.findSocket.byPID(socketInfo.PARTYID.get(id)); + public static void sendParty(Integer socketid) throws ctException{ + JsonObject main = buildEvent(socketid); + if(main == null){return;} + ArrayList a = SocketMaps.getAllParty(SocketMaps.getPID(socketid)); for (int i = 0; i < a.size(); i++) { - JsonObject c = creator.build(); - socketInfo.CLIENT.get(a.get(i)).sendSocket(c.toString()); + SocketMaps.getClient(a.get(i)).writeSocket(main.toString()); + Console.socket(a.get(i),main.toString()); } } - public static void wind(Integer sid){ - int id = socketInfo.findSocket.bySID(sid); - if(id == -1){return;} - JsonObjectBuilder creator = Json.createObjectBuilder(); - creator.add("EVENT", "wind"); - creator.add("tm",socketInfo.TIME.get(id)); - creator.add("tI", socketInfo.TRACKID.get(id)); - creator.add("tT", socketInfo.TRACKTIME.get(id)); - creator.add("tD", socketInfo.DURATION.get(id)); - creator.add("ps", false); - eventSender(id,creator); - } - - } diff --git a/src/socketInfo.java b/src/socketInfo.java deleted file mode 100644 index e1bd41e..0000000 --- a/src/socketInfo.java +++ /dev/null @@ -1,188 +0,0 @@ -import com.sun.istack.internal.NotNull; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.function.BooleanSupplier; - -/** - * Created by itsmy_000 on 13.08.2016. - */ -public class socketInfo { -// public enum EVENT{PLAY,NEXT,REWIND,PAUSE,PREV,SCROB} -// public static ArrayList EVENTS; - public static ArrayList TIME, TRACKTIME; - public static ArrayList PROTOCOL, EVENT, TRACKID; - public static ArrayList ROLE, VKID, SOCKETID, PARTYID, DURATION; - public static ArrayList ONLINE, httpAuth, protocolAuth, AUTOPLAY; - public static ArrayList CLIENT; - public static Integer sid; - - - public static void init(){ - sid = 0; - VKID = new ArrayList<>(); - TIME = new ArrayList<>(); - TRACKTIME = new ArrayList<>(); - ROLE = new ArrayList<>(); - EVENT = new ArrayList<>(); - CLIENT = new ArrayList<>(); - PARTYID = new ArrayList<>(); - TRACKID = new ArrayList<>(); - PROTOCOL = new ArrayList<>(); - DURATION = new ArrayList<>(); - SOCKETID = new ArrayList<>(); - ONLINE = new ArrayList<>(); - httpAuth = new ArrayList<>(); - protocolAuth = new ArrayList<>(); - AUTOPLAY = new ArrayList<>(); - } - - public static void create(client c, Integer sid){ - VKID.add(0); - TIME.add(BigDecimal.ZERO); - TRACKTIME.add(BigDecimal.ZERO); - ROLE.add(1); - EVENT.add(""); - ONLINE.add(true); - CLIENT.add(c); - TRACKID.add(""); - PROTOCOL.add(""); - PARTYID.add(0); - DURATION.add(0); - SOCKETID.add(sid); - httpAuth.add(false); - protocolAuth.add(false); - AUTOPLAY.add(false); - } - - public static void close(Integer sid){ - int s = findSocket.bySID(sid); - VKID.remove(s); - ROLE.remove(s); - PROTOCOL.remove(s); - EVENT.remove(s); - TRACKID.remove(s); - SOCKETID.remove(s); - TIME.remove(s); - TRACKTIME.remove(s); - DURATION.remove(s); - PARTYID.remove(s); - CLIENT.remove(s); - ONLINE.remove(s); - httpAuth.remove(s); - protocolAuth.remove(s); - AUTOPLAY.remove(s); - } - - public static Integer getNewID(){ - sid++; - return sid; - } - - public static class findSocket extends socketInfo{ - - public static Integer bySID(Integer s){ - int id = -1; - for (int i = 0; i < SOCKETID.size(); i++) { - if(SOCKETID.get(i).equals(s)){ - id = i; - } - } - return id; - } - - public static ArrayList byPID(Integer pid){ - ArrayList a = new ArrayList<>(); - for (int i = 0; i < PARTYID.size(); i++) { - if(PARTYID.get(i).equals(pid)){ - a.add(i); - } - } - return a; - } - - } - - public static void setHttpAuth(Integer sid, Boolean b){ - int s = findSocket.bySID(sid); - if(s == -1) return; - httpAuth.set(s, b); - } - - public static void checkProtocol(Integer sid){ - int s = findSocket.bySID(sid); - if(s == -1) return; - if(PROTOCOL.get(s).equals("1A")){ - protocolAuth.set(s, true); - } - } - - public static Boolean isProtocolAuth(Integer sid){ - int s = findSocket.bySID(sid); - if(s == -1) return Boolean.FALSE; - return protocolAuth.get(s); - } - - public static Boolean isHttpAuth(Integer sid){ - int s = findSocket.bySID(sid); - if(s == -1) return Boolean.FALSE; - return httpAuth.get(s); - } - - public static Boolean isOnline(Integer sid){ - int s = findSocket.bySID(sid); - if(s == -1) return Boolean.FALSE; - return ONLINE.get(s); - } - - public static client getClient(Integer sid){ - int s = findSocket.bySID(sid); - if(s == -1) return null; - return socketInfo.CLIENT.get(s); - } - - public static void setString(Integer sid, String keyName, String value) { - int s = findSocket.bySID(sid); - if (s == -1) return; - switch (keyName) { - case "EVENT": - EVENT.set(s, value); - break; - case "tI": - TRACKID.set(s, value); - break; - case "protocol": - PROTOCOL.set(s, value); - break; - } - } - - public static void setInteger(Integer sid, String keyName, BigDecimal value){ - int s = findSocket.bySID(sid); - if(s == -1) return; - switch (keyName){ - case "vk_id": VKID.set(s, value.intValueExact()); - break; - case "tm": TIME.set(s, value); - break; - case "tT": TRACKTIME.set(s, value); - break; - case "partyId": PARTYID.set(s, value.intValueExact()); - break; - case "tD": DURATION.set(s, value.intValueExact()); - break; - } - } - - public static void setBoolean(Integer sid, String keyName, Boolean value){ - int s = findSocket.bySID(sid); - if(s == -1) return; - switch (keyName) { - case "aP": - AUTOPLAY.set(s, value.booleanValue()); - break; - } - - } -}