Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.athena.network; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; import com.athena.logic.SPlayingTable; import com.athena.logic.User; import com.athena.util.Log; import com.cubeia.firebase.api.util.ParameterUtil; import com.cubeia.firebase.clients.java.connector.Connector; import com.cubeia.firebase.clients.java.connector.SocketConnectorFactory; import com.cubeia.firebase.io.ProtocolObject; import com.cubeia.firebase.io.protocol.CreateTableRequestPacket; import com.cubeia.firebase.io.protocol.Enums.LobbyType; import com.cubeia.firebase.io.protocol.GameTransportPacket; import com.cubeia.firebase.io.protocol.JoinRequestPacket; import com.cubeia.firebase.io.protocol.LeaveRequestPacket; import com.cubeia.firebase.io.protocol.LobbySubscribePacket; import com.cubeia.firebase.io.protocol.LobbyUnsubscribePacket; import com.cubeia.firebase.io.protocol.LoginRequestPacket; import com.cubeia.firebase.io.protocol.Param; import com.cubeia.firebase.io.protocol.PingPacket; import com.cubeia.firebase.io.protocol.ServiceTransportPacket; import com.dst.game.GameActivity; import com.dst.ui.dautruong.LobbyDT; import com.dst.ui.fun52.Lobby52Fun; import com.dst.ui.langquat.GameOption; import com.dst.ui.langquat.SActivity; import com.dst.ui.langquat.WaitingRoom; import com.dst.ui.threeC.WaitingRoom3C; /** * * @author annguyen */ public class CubeiaClient { public static final int PORT = 4123; public static String HOST = "203.162.166.23"; // public static String HOST = "192.168.1.109"; private String LOBBY_NEW = ""; private String LOBBY_OLD = ""; public long lastTimeConnected; private Connector connector; private static CubeiaClient client; public static CubeiaClient getInstance() { if (client == null) client = new CubeiaClient(); return client; } private void send(final ProtocolObject packet) { if (packet instanceof ServiceTransportPacket) { ServiceTransportPacket serviceTransportPacket = (ServiceTransportPacket) packet; String json = fromUTF8Data(serviceTransportPacket.servicedata); Log.d("--> send", json); } else if (packet instanceof GameTransportPacket) { GameTransportPacket gameTransportPacket = (GameTransportPacket) packet; String json = fromUTF8Data(gameTransportPacket.gamedata); Log.d("--> send", json); } else { Log.d("--> send", packet.toString()); } new Thread(new Runnable() { @Override public void run() { if (connector != null && connector.isConnected()) { synchronized (connector) { connector.send(packet); } } } }).start(); } public void sendServicePacket(String data) { ServiceTransportPacket packet = new ServiceTransportPacket(); packet.service = "com.athena.services.api.ServiceContract"; try { packet.servicedata = data.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } packet.pid = 11111; packet.seq = 1; packet.idtype = 1; send(packet); } public void sendDataGame(JSONObject ojbect) { GameTransportPacket gameTransportPacket = new GameTransportPacket(); gameTransportPacket.pid = User.pId;// PlayerTala.getInstance().get_userid(); gameTransportPacket.tableid = User.tableId; gameTransportPacket.gamedata = ojbect.toString().getBytes(); send(gameTransportPacket); } public void loginToGame() // ok { final JSONObject user = new JSONObject(); try { user.put("Userid", 1); user.put("Username", "ann101"); user.put("Signid", "qazwsxedcrfv123$%^789");// qzawsxedcrfvtgb123$%^ user.put("From", "mbacay"); user.put("gameid", 8006); user.put("deviceId", "c1072d17963e42e3"); } catch (JSONException e) { e.printStackTrace(); } LoginRequestPacket packet = new LoginRequestPacket(); packet.user = user.toString(); packet.password = "hihihehe"; packet.operatorid = 110; send(packet); System.out.println("--> Login Packet sent: " + packet.toString()); } public void login(final String user, final String pass, final int operid) { // TODO check if connector is not connected, then make a connection sendLogout(); new Thread(new Runnable() { @Override public void run() { // postToUI("?ang kt ni n server"); SocketConnectorFactory socketConnectorFactory = new SocketConnectorFactory(HOST, PORT); try { connector = socketConnectorFactory.createConnector(); connector.addListener(new PacketHandler(CubeiaClient.this)); connector.connect(); } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } if (connector.isConnected()) { // postToUI("Kt ni server thnh cng."); try { LoginRequestPacket packet = new LoginRequestPacket(); packet.user = user; packet.password = pass; packet.operatorid = operid; send(packet); } catch (Exception ex) { ex.printStackTrace(); } } else { // postToUI("Kt ni server tht bi."); } } }).start(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } while (true) { // qua 30s khong nhan dc tin hieu if (System.currentTimeMillis() - lastTimeConnected > 20000) { SActivity.getCurrentScreen().runOnUiThread(new Runnable() { @Override public void run() { if (SActivity.DEBUG == false) SActivity.getCurrentScreen().lostConnection(); } }); lastTimeConnected = System.currentTimeMillis(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (connector.isConnected()) { // System.out.println(Thread.currentThread().getName() + " connected"); } else { // show Toast to user User.getSActivity().runOnUiThread(new Runnable() { @Override public void run() { SActivity atc = User.getSActivity(); if (atc instanceof SPlayingTable || atc instanceof GameOption || atc instanceof WaitingRoom || atc instanceof GameActivity || atc instanceof WaitingRoom3C || atc instanceof LobbyDT || atc instanceof Lobby52Fun) atc.lostConnection(); } }); System.out.println("not connected"); break; } } } }).start(); } public void sendSelectGame() { try { JSONObject data = new JSONObject(); data.put("evt", "selectG"); data.put("gameid", User.gameId); sendServicePacket(data.toString()); System.out.println("sendSelectGame" + data.toString()); } catch (JSONException e) { e.printStackTrace(); } } void replyPing(int id) { send(new PingPacket(id)); } public void registryLobby() { LOBBY_OLD = LOBBY_NEW; LOBBY_NEW = User.levelId + "/" + User.roomId; if (LOBBY_OLD.length() > 0) unRegistryLobby(); LobbySubscribePacket packet = new LobbySubscribePacket(); packet.type = LobbyType.REGULAR; packet.gameid = User.gameId;// MyGame.getInstance().getGAMEID(); packet.address = LOBBY_NEW; send(packet); unRegistryLobby(); } public void unRegistryLobby() { LobbyUnsubscribePacket packet = new LobbyUnsubscribePacket(); packet.type = LobbyType.REGULAR; packet.gameid = User.gameId;// MyGame.getInstance().getGAMEID(); packet.address = LOBBY_OLD; send(packet); } public void unRegistryCurLobby() { LobbyUnsubscribePacket packet = new LobbyUnsubscribePacket(); packet.type = LobbyType.REGULAR; packet.gameid = User.gameId;// MyGame.getInstance().getGAMEID(); packet.address = LOBBY_NEW; send(packet); } public void sendCreateTableRequest(int stake, int agMin, int maxPlayer, int vipMin, JSONObject jobj) { unRegistryLobby(); CreateTableRequestPacket packet = new CreateTableRequestPacket(); packet.gameid = User.gameId; packet.seats = (byte) maxPlayer; packet.seq = 1; packet.invitees = new int[0]; packet.params = new ArrayList<Param>(); try { if (jobj == null) { jobj = new JSONObject(); } jobj.put("gameId", User.gameId); jobj.put("Name", "nhao` zo^ !"); jobj.put("Mark", stake); jobj.put("gaAGmeId", agMin); jobj.put("Vip", vipMin); jobj.put("Player", maxPlayer); @SuppressWarnings("unchecked") Iterator<String> i = jobj.keys(); while (i.hasNext()) { String nparam = i.next(); Object oparam = jobj.get(nparam); Param param = ParameterUtil.createParam(nparam, oparam); packet.params.add(param); } } catch (JSONException e) { e.printStackTrace(); } send(packet); } public void sendJoinTable(int id) { unRegistryLobby(); JoinRequestPacket packet = new JoinRequestPacket(); packet.tableid = id; packet.seat = -1; send(packet); } public void sendQuickJoinGame() { try { JSONObject data = new JSONObject(); data.put("gameid", User.gameId); data.put("evt", "searchT"); sendServicePacket(data.toString()); } catch (JSONException e) { e.printStackTrace(); } } public void sendLeaveTable() { LeaveRequestPacket packet = new LeaveRequestPacket(); packet.tableid = User.tableId;// MyGame.getInstance().getTABLEID(); send(packet); } public void sendLogout() { // LogoutPacket logoutPacket = new LogoutPacket(true); // send(logoutPacket); if (connector != null && connector.isConnected()) connector.disconnect(); } private String fromUTF8Data(byte[] arr) { try { return new String(arr, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Missing UTF-8?!"); } } public void setLastTimeConnected() { lastTimeConnected = System.currentTimeMillis(); // SActivity.getCurrentScreen().dismissSDialog(); } }