How to design an excellent j2's software and how to crack the secrets of online games on the j2's mobile phone

Source: Internet
Author: User
How to design an excellent j2_software
-------------------------
Java me technology has been around for many years now. During this time, everyone has mixed comments on this technology. We will not discuss this for the time being. I will use my project experience today. How to design an excellent java me mobile phone software. This article is not a purely technical article. Anyone who has worked on a project can see it clearly. The point in this article is just the personal point of view of the Code. I hope you will give more instructions on what is wrong.

First, let's talk about the situation of the advanced UI application of J2EE:

1. The game does not use the advanced UI at all. It only uses the advanced UI to call the localInput Method.

2. Enterprise applications require high interaction, fast real-time, and user-friendly applications. For applications with user-friendly interfaces, the application of advanced UI is good for game queries.

3. Simple examples and tutorials won't be availableMobile phoneSoftware, most of which adopt advanced UI, because the advanced UI is simple and easy to describe.

In conclusion, the advanced UI is not suitable for enterprise applications and game development.

Examples include UCWEB, navigators, Fadato football clients, and Bobi football instant.Tools, QQ series software, online live broadcast, mobile phone entertainment software, Mino mail client, etc... This series proves that there are not many advanced UI applications. Software is the most used in these systems.Configuration, Input method calls, error prompts (Alert), etc.

 

Successful establishment of JSR specifications.

Although the development of mobile phone software is not as heavy as the development of computer software, there are no less things to consider than computer software. The reasons are as follows:

1. hardware configuration is far inferior to that of a computer

2. The operating system is too scattered

 

JSR appears for these differences.

You can queryApiTo check whether your mobile phone has such a function, and make a choice.

 

The above is nonsense. Let's take a look at how to design a good software.

1. User-friendly and customizable UI components.

2. Reasonable user operation logic and professional planning and organization

3. A set of reasonable memory management to ensure the stability of the software

4. Software Architecture Pattern to adapt to requirements.

5. good performance.

 

The above is the basic condition of a software. To make this software widely interpreted, we still need to solve the following problems:

1. Mobile phone models are supported. Try to match multiple models. If you cannot guarantee that all models are supported, you can at least support mobile phones of mainstream mobile phone manufacturers.

2. you can customize some special services for each model. For example, if some mobile phones support JSR75, you can consider saving more things to your mobile phone. If some do not, you can consider using RMS, some support multiple media types, and you can also customize multi-point services for such mobile phones.

3. A good product must have a community to support, so a popular product community is indispensable.

4. I personally feel that the standalone version of the software cannot achieve great success. We must use the C/S method to obtain the user's product viscosity.

5. rome cannot be built in just one day, so the software is not perfect as soon as it comes out, so it is important to constantly update and maintain the software, one of the criteria of good software is to see what version the software has developed. The version is also high, proving that your software is becoming more active.

-------------------------------
How to resolve the problems caused

Preface:
Real knowledge in ChinaMobile phoneOnline Game CoreTechnologyThere are not many companies, and there are even a few people who can independently construct mobile online game clients and servers. These materials are also considered confidential by many companies.Open SourceFrom the networkGamesThe "fruit machine", to the socket-based "Slug", basically explains some technical details. After reading this, it is also ambiguous.
For work reasons, I have been engaged in Mobile Online Game Development since I started my work. Although not proficient, I know what it means to myself. So here we will not share this knowledge and contribute it to everyone. In order to drive the popularity of the j2s forum.
I will start with "fruit machine" and "Slug", then talk about my own architecture and methods, and make a comparison. This gives you a better understanding of the technical details and overall architecture.
Due to the time, I am too busy to work on it. I may write a little bit occasionally, hoping to get your support.

(1) HTTP-based mobile online games
Because all MIDP specifications stipulate that HTTP must be supported. According to industry insiders, China Telecom will only support HTTP in the future, therefore, many mobile online games are built on HTTP. But because of the integrity of HTTP protocol encapsulation, it brings benefits and disadvantages.

First, let's look at the advantages of HTTP:
1: The servelt container will automatically manage the thread pool. In our program, you do not have to manage the thread on your own. Of course, the thread I am talking about is a thread generated by the client to connect to the server.
2: HTTP is secure. session is used to manage each session, saving the headache of client impersonating.
3: almost all supportedJavaAll mobile phones support the HTTP protocol.
Of course, there are other advantages. I can't come here one by one. Let's try it myself ......

The second is the disadvantages of the HTTP protocol:
1: the connectivity of the HTTP protocol is a headache for everyone. Someone once mentioned how to modify the HTTP protocol. I don't know if it succeeded? Of course, this is beyond the scope of our discussion.
2: It is the problem of network traffic, which is also a headache for everyone. If it is not a monthly subscription, this is indeed a large expense for users.

Next I will explain the architecture of the client and server of the famous mobile online game "fruite-machine:

Phone --------------- → Servlet ------------------ → Web Browser

The figure above shows the overall architecture of the "fruit machine.
"Fruit machine" was once popular in various video game halls and appeared as a gambling machine. This game is easy to design, but it is quite playable. It is a classic game comparable to "Tetris.

The web Browser layer behind the architecture is used to manage the user's web interface and can be operatedDatabaseTo manage users.

Because Users enter "username" and password "on their mobile phones during login, security is a big problem.
In the design document in fruite-machine, this problem is solved:
1. Use end-to-end encrypted connections to replace HTTP
2: based on a secureWirelessThe network uses HTTP to transmit username and password to the servlet end through a secure wireless gateway.
3: Send the username and password in the same firewall as the servlet.

To solve the problem of user spoofing, a user may put the MIDlet ClientDownloadModify laterSource codeIn this way, fake packets may be sent to the servlet end. Some data that may be modified by the user is generated on the servlet end and then transmitted to the MIDlet, so that the user cannot modify the data. For example, the MIDlet does not generate a result that rotates immediately, but is generated by the server.

(2)
The Protocol for communication is actually a rule agreed between the client and the server for communication. Because both the client request and Server Response content are in the HTTP body, and the body is only a byte stream, the client and server must be consistent in understanding these byte streams.

In Fruite-machine, Delimiter is used to represent a new line of character information. If the new character information needs to be isolated, \ is used for isolation.

Therefore, the entire sent message looks like this: login logs drap logs secret

As an example, let's take a look at the interaction process between the player and the server after selecting a pet:
MIDelt --------------------- servlet
First, the MIDlet sends a rotation request to the servlet server. The request body contains the location of the selected PET and the flag (true or false) under the pet ).
After receiving the packet, the server processes the packet. And return the corresponding message according to the processing result. If the player wins, the server returns the player's winning position, the bonus points, and the position where the player stops after rotation. If it fails, the server returns a failed message to the player.

I will not talk about the client program. I will focus on the server program.
Next let's take a look at the overall structure:
When the fruitemachineservlet receives a Request, it first analyzes the Request from the mobile terminal or the web management page, and sends the Request to the corresponding program for processing. Web page requests are mainly used to update databases. Mobile Terminal requests first analyze the request type: Login, game, or other ...... And give them to the corresponding program for processing. If it is a login, the game processor will retrieve the user's username and password from the database and verify the user. And generate a new HTTPsession session to manage the connection. If the user exits, the game logic will destroy Httpsession.
First, let's look at the servlet program:
Import java. io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;

Public class FruitMachineServelt extends HttpServlet {
Private UserDatabase userDatabase;
Private AdminProtocolHandler adminProtocolHandler;
Private GameProtocolHandler gameProtocolHandler;

Public void init (ServletConfig config) throws ServletException {
Super. init (config );
UserDatabase = new UserDatabase ();

UserDatabase. createUser ("guest ","");

AdminProtocolHandler = new AdminProtocolHandler (userDatabase );
GameProtocolHandler = new GameProtocolHandler (userDatabase );
}

Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws IOException, ServletException {
Try {
String pathInfo = request. getPathInfo ();
If (pathInfo = null ){
Reponse. sendError (HttpServletResponse. SC _BAD_REQUEST, "Missing path info ");
} Else if (pathInfo. startsWith ("/admin ")){
AdminProtocolHandler. doGet (request, response );
} Else {
Response. sendError (HttpServletResponse. SC _BAD_REQUEST, "Unexpected path info ");
}
} Catch (IOException e ){
E. printStackTrace ();
Throw e;
} Catch (Exception e ){
E. printStackTrace ();
Throw new ServletException (e. getMessage ());
}
}

(3)
If you have time today, write a bit more.
Fruite-machine strictly speaking, it is just a game with high and low scores. It is not a real online game, but it also implements some simple functions of online games.

Although Fruite-machine uses the HTTP protocol, it does not round-robin the server. Instead, it sends a packet to the server through callback and then receives another packet for processing. In this way, problems may occur in real online games, because in real online games, servers may send messages to a player. In fruite-machine, the server cannot actively send messages to players. It only calls back the response function when the user sends messages to the server, this is a one-Answer message transmission method.

Strictly speaking, in a real online game, the HTTP protocol can only be used in the round-robin server mode to solve the problem that the server actively sends packets to a client. Is the so-called heartbeat packet.

Next let's look at the program that implements the callback function:
Import java. io .*;
Import java. util .*;
Import javax. microedition. io .*;

/**
* This class accepts and queues POST requests for a participant URL, and
* Services them in first-in-first-out order. Using the queue allows it
* To be thread-safe without forcing its clients ever to block.
*/
Public class HttpPoster
Implements Runnable
{
Private String url;
Private volatile boolean aborting = false;
Private Vector requestQueue = new Vector ();
Private Vector listenerQueue = new Vector ();

Public HttpPoster (String url)
{
This. url = url;
Thread thread = new Thread (this );
Thread. start ();
}

Public synchronized void sendRequest (String request,
HttpPosterListener listener)
Throws IOException
{
RequestQueue. addElement (request );
ListenerQueue. addElement (listener );
Running y (); // wake up sending thread
}

Public void run ()
{
Running:
While (! Aborting)
{
String request;
HttpPosterListener listener;

Synchronized (this)
{
While (requestQueue. size () = 0)
{
Try
{
Wait (); // releases lock
}
Catch (InterruptedException e)
{
}

If (aborting)
Break running;
}

Request = (String) (requestQueue. elementAt (0 ));
Listener = (HttpPosterListener) (listenerQueue. elementAt (0 ));
RequestQueue. removeElementAt (0 );
ListenerQueue. removeElementAt (0 );
}

// SendRequest must have notified us
DoSend (request, listener );
}
}

Private void doSend (String request,
HttpPosterListener listener)
{
HttpConnection conn = null;
InputStream in = null;
OutputStream ut = null;
String responseStr = null;
String errorStr = null;
Boolean wasError = false;

Try
{
Conn = (HttpConnection) Connector. open (url );

// Set the request method and headers
Conn. setRequestMethod (HttpConnection. POST );
Conn. setRequestProperty ("Content-Length", Integer. toString (request. length ()));

// Getting the output stream may flush the headers
Ut = conn. openOutputStream ();
Int requestLength = request. length ();
For (int I = 0; I <requestLength; ++ I)
{
Out. write (request. charAt (I ));
}

// Opening the InputStream will open the connection
// And read the HTTP headers. They are stored
// Requested.
In = conn. openInputStream ();

// Get the length and process the data
StringBuffer responseBuf;
Long length = conn. getLength ();
If (length> 0)
{
ResponseBuf = new StringBuffer (int) length );
}
Else
{
ResponseBuf = new StringBuffer (); // default length
}

Int ch;
While (ch = in. read ())! =-1)
{
ResponseBuf. append (char) ch );
}
ResponseStr = responseBuf. toString ();

// Support URL rewriting for session handling
String rewrittenUrl = conn. getHeaderField ("X-RewrittenURL ");
If (rewrittenUrl! = Null)
{
Url = rewrittenUrl; // use this new one in future
}
}
Catch (IOException e)
{
WasError = true;
ErrorStr = e. getMessage ();
}
Catch (SecurityException e)
{
WasError = true;
ErrorStr = e. getMessage ();
}
Finally
{
If (in! = Null)
{
Try
{
In. close ();
}
Catch (IOException e)
{
}
}
If (out! = Null)
{
Try
{
Out. close ();
}
Catch (IOException e)
{
}
}
If (conn! = Null)
{
Try
{
Conn. close ();
}
Catch (IOException e)
Listener. receiveHttpResponse (responseStr );
{
}
}
}

If (wasError)
{
Listener. handleHttpError (errorStr );
}
Else
{
Listener. receiveHttpResponse (responseStr );
}
}

// This is just for tidying up-the instance is useless after it has
// Been called
Public void abort ()
{
Aborting = true;
Synchronized (this)
{
Running y (); // wake up our posting thread and kill it
}
}
}
From the HttpPoster class, we can see that the HttpPoster class uses a separate thread. As long as the sendRequest (String request, HttpPosterListener listener) method of the HttpPoster class is called, the thread will run, call the doSend (String request, HttpPosterListener listener) method to send the request to the server.

Note listener. receiveHttpResponse (responseStr); this program calls back the receiveHttpResponse (String response) method of HttpPosterListener. polymorphism is also used here. listener calls the receiveHttpResponse (String reponse) method to process the packets returned by the server.

I wrote this article today. In short, the HttpPoster class is well written and deserves your attention. Including multi-threaded wait () and notify () mechanisms.

This topic provides an in-depth explanation of this keyword and its main functions.

For the first time, anyone who comes into contact with programming will be confused about the usage and meaning of this keyword.

In this article, I will give you a profound analysis of its meaning and functions.

Literally, this refers to itself, so it also refers to an instance of itself in the program. In fact, it is essentially an implicit pointer of the java class, but before the instance is generated, it does not point to the specific memory. This can also be used in the class.

System. out. println (this );

View the output, and the output is null.

It points to a specific instance with the generation of a specific instance, and allocates corresponding storage units for it in the memory.

Well!

I don't know whether you understand the usage of this. In the end, it is a pointer pointing to yourself. As an object is generated, it points to a specific object instance and disappears as the object disappears.

Since it is an object, we can imagine that this is used inObject-orientedIn programming.

Let's take a look at the usage of this:

1: distinguish between global variables and local variables

We know that if a function contains a local variable with the same name and type as the global variable, the global variable is invisible to this method.

As follows:

Public class Test {

Int a, B;

Public void change (int a, int B ){

A =;

B = B;

}

}

We originally meant to use the change () method to change the values of global variables a and B. However, due to name conflicts, the global variables are invisible to the chang () method, that is, overwrite.

But what if this is the case?

Public void change (int a, int B ){

This. a =;

This. B = B;

}

Then the compiler knows that we need to change the values of a and B through the change () method. You should not think that the compiler is very intelligent. In fact, it is very stupid. When your program is confused, it will be silly and do not know how to deal with it!

The this keyword clearly indicates that we want to change the values of global variables a and B.

2: act as an instance in some startup classes

As we know, the MIDlet is the startup class of j2's.

The compiler automatically starts it, so we cannot come out with a new MIDlet. This is not allowed by the compiler!

Because you do this, it doesn't know where to start it! As I said, the compiler is stupid. You should not think it is very clever. In many cases, it is confusing!

At this time, the only way is to input the this keyword where the MIDlet object instance is required. When the compiler starts and generates the MIDlet instance, the corresponding this points to the generated instance, this allows us to manipulate our MIDlet object and call its method.

For example:

Public class SpaceShooter extends MIDlet {

Private GameCanvas gameCanvas;

Public SpaceShooter (){
GameCanvas = new GameCanvas (this); // input the implicit pointer of the current class, which is passed in when the MIDlet is generated, so that the MIDlet method can be called in GameCanvas.
Display. getDisplay (this). setCurrent (gameCanvas );
}

/** Method called at the beginning of the MIDlet */
Protected void startApp () throws MIDletStateChangeException {
GameCanvas. doStartApp ();
}

/** Method called when the MIDlet is paused */
Protected void pauseApp (){
GameCanvas. doPauseApp ();
}

/** Method called at the end of the MIDlet */
Protected void destroyApp (boolean unconditional)
Throws MIDletStateChangeException {}

/** Method called when the MIDlet is ended */
Void doExit (){
Try {
DestroyApp (false );
Yydestroyed ();
} Catch (MIDletStateChangeException e ){}
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.