Android Study Notes: Analysis of the Design Philosophy of your chat system

Source: Internet
Author: User

In today's society where there are more materials such as Ox hair and more cattle people than data, it is not difficult to use code to make something. If it is a little difficult, just go to various professional forums and various technical groups, everyone will discuss things that are hard to solve. We can learn the technology, but it is difficult to think about it. The same book has different experiences and insights from different people, the ideas of those cool people are embodied after countless rich codes (so we admire the cool guys who announce their painstaking efforts. We need to learn this kind of dedication ), how can we quickly comprehend the design ideas of cool people is undoubtedly a huge difficulty for cainiao like ours. With the selfless dedication of the cool people, our learning is doomed to get twice the result with half the effort, we can understand profound ideas without the training of devil-like code, which will benefit us a lot.
In a learning attitude and in order to record your own sentiment, I will analyze the design idea of a chat application that I have developed here, so that I can review it later.
UDP communication protocol, which is not described here.
The following simple figure shows how to design it:

 
It can be seen that the entire system is divided into seven modules: View, message processor, message parser, UDP Service, resolution controller, processing controller, and message body.
The entire process sequence:
1. Register a message processor in the Activity to process received messages and display the results in the Activity;
2. When sending a message, we need to encapsulate our information into a message package.
3. If the message package needs to be transmitted over udp, it must be parsed by a specific parser to obtain a transmission protocol. Of course, the parser must also have a decoding code, the rules must be the same.
4. process and analyze the preceding transmission protocol here
5. Call the resolution Controller
6. The parsing controller calls the corresponding parser to decode the Response Message package through some labels in the Protocol.
7. Call the processing controller and pass the Response Message package obtained above
8. Respond to some marks in the message package to determine whether to call the corresponding processor for processing, and obtain the information and display it.
 
Note:
1. There are many types of message msg, for example, you may want to send a message packet to the CIDR block to ask who is online, who is responding to the Message package online, who has a chat message package, or who has personal information to view the request message package.
For example, WHO has an online message package WhoOnlinePackage:
[Java]
Public class WhoOnlinePackage extends MsgPackage {
 
Private String mac;
Private String nickName;
Private int portrait;
@ Override
Public Integer getMsgCode (){
Return MsgCode. WHOONLINE;
}
 
 
Public WhoOnlinePackage (String nickName, String mac, int portrait ){
This. mac = mac;
This. nickName = nickName;
This. portrait = portrait;
}
 
 
Public String getMac (){
Return mac;
}
 
 
Public void setMac (String mac ){
This. mac = mac;
}
 
 
Public String getNickName (){
Return nickName;
}
 
 
Public void setNickName (String nickName ){
This. nickName = nickName;
}
 
 
Public int getPortrait (){
Return portrait;
}
 
 
Public void setPortrait (int portrait ){
This. portrait = portrait;
}
 
 
Public WhoOnlinePackage (){}


 
}

 
2. If there are many types of message packets, there will be several types of Resolvers, each of which performs different encoding and decoding for different msg.
For example, who has the online message package Parser:
[Java]
Public class WhoOnlinePackageParser extends MsgPackageParser <WhoOnlinePackage> {
 
@ Override
Public WhoOnlinePackage decode (PackageInputStream in) throws IOException {
Return new WhoOnlinePackage (in. readString (10, CHARSET), MsgPackageUtils. getLongMacToString (in. readLong (), in. readInt ());
}
 
@ Override
Public void encode (WhoOnlinePackage obj, PackageOutputStream out) throws IOException {
Out. writeString (obj. getNickName (), 10 );
Out. writeLong (MsgPackageUtils. getStringMacToLong (obj. getMac ()));
Out. writeInt (obj. getPortrait ());
}
}
In the parser, encoding and decoding are performed according to the rules of the transport protocol.
3. The number of processors is the same as the number of parser types. The processor processes the message package parsed by the parser and displays the result.
For example, the implementation of the processor in the Activity:
[Java]
@ Override
Public void onMsgReceived (MsgPackage msgPackage ){
Switch (msgPackage. getMsgCode ()){
Case MsgCode. WHOONLINE:
WhoOnlinePackage wpck = (WhoOnlinePackage) msgPackage; // obtain the online message package that someone else asks.
ImOnlinePackage ipck = new ImOnlinePackage (preferences. getString ("nick", DicqConstant. LOCALNAME), preferences. getString ("mac", DicqConstant. defamac Mac), preferences. getInt ("portrait", getLocalInfo (). getPortrait (); // responds to his/her online message package and encapsulates local information
Ipck. addTargetIp (wpck. getFromIp ());
SendMsgPackage (ipck, wpck. handlerTag );
Int wteamid =-1;
Team wteam = service. getTeamByMac (wpck. getMac ());
If (wteam = null ){
Try {
Wteamid = service. find ("weimingming"). getTeamId ();
} Catch (Exception e ){
E. printStackTrace ();
}
} Else {
Wteamid = wteam. getTeamId ();
}
UserInfo wuser = new UserInfo ();
Wuser. setTeamid (wteamid );
Wuser. setUserip (wpck. getFromIp ());
Wuser. setUsermac (wpck. getMac ());
Wuser. setUsername (wpck. getNickName ());
Wuser. setPortrait (wpck. getPortrait ());
Wuser. setPersonsign ("brother is just a legend"); // encapsulate the information into a user object
Service. saveUserMac (wpck. getMac (), wteamid );
AddUserToList (wuser );
If (! Wpck. getMac (). equalsIgnoreCase (DicqConstant. defamac Mac )){
Toast. makeText (TeamMainActivity. this, wuser. getUsername () + "launched! ", Toast. LENGTH_LONG). show ();
}
Adapter. setData (service. getTeamList (), userList );
Adapter. notifyDataSetChanged (); // refresh, display
Break;

 
4. The resolution controller and processing controller do not need to focus on all the Resolvers and processors, but use a single sign to focus on the resolution and processors they are interested in. This resolution is already registered during Activity.
For example, register the parser in Activity:
[Java]
@ Override
Public void onServiceConnected (){
Register (MsgCode. WHOONLINE,-1); // register to ask who is online parser
Register (MsgCode. IONLINE,-1); // register the online Parser for the response
Register (MsgCode. SINGLECHAT,-1); // register the single chat parser
Register (MsgCode. IMGOAWAY,-1); // register the offline parser
}

 
Resolution controller:
[Java]
**
* Message parsing Controller
*
*/
Public abstract class MsgPackageParserController {

/**
* Parse a message
* @ Param buf
* @ Param offset
* @ Param length
* @ Return
*/
Public abstract MsgPackage messageDecode (PackageInputStream in) throws IOException;

/**
* Encode the message
* @ Param command
* @ Return
*/
Public abstract void messageEncode (MsgPackage command, PackageOutputStream out) throws IOException;


}

Processing controller:
[Java]
/**
* Message processing controller
*
*/
Public abstract class MsgPackageProcessor {

/**
* Register a message processor
* @ Param handler
* @ Param tag indicates the identifier of the processor, which is used to maintain the Session of the same message from different devices.
*/
Public abstract void registMessageHandler (MsgPackageHandler <MsgPackage> handler, Integer tag );

/**
* Cancel the message processor.
* @ Param msgCode indicates the message type that the processor is interested in.
* @ Param tag indicates the identifier of the processor, which is used to maintain the Session of the same message from different devices.
*/
Public abstract void unRegistMessageHandler (Integer msgCode, Integer tag );

/**
* Process messages
* @ Param msgPackage
*/
Public abstract void processMessage (MsgPackage msgPackage );
}
 
5. transmission protocols are important. Different transmission protocols are developed based on your understanding.
6. udp server is responsible for scheduling. When a message comes, call the resolution controller to generate a corresponding parser to parse the message to get a message package, then, it is handed over to the processing controller to generate a message package generated by the corresponding processor processing parser. The key code is as follows:
[Java]
/*
* Message loop
*/
@ Override
Public void run (){
Isrun = true;
While (isrun &&! Socket. isClosed ()){
Byte [] buf = new byte [MAXBUFFSIZE];
Required rampacket packet = new DatagramPacket (buf, MAXBUFFSIZE );
Try {
Socket. receive (packet );
ProcessUnresolvedMessage (buf, 0, packet. getLength (), packet. getAddress ());
} Catch (IOException e ){
E. printStackTrace ();
}
}
}

/**
* Parse and process messages sent from a remote device.
* Message parsing Controller: parse a message
* Message processing controller: Processes messages.
*/
@ Override
Public void processUnresolvedMessage (byte [] msgPackage, int offset, int length, InetAddress fromIp ){
MsgPackage m = null;
Try {
M = messageParser. messageDecode (new PackageInputStream (msgPackage, offset, length); // parse it into a message package
} Catch (Exception e ){
Log. e (TAG, "command decode exception", e );
}
If (m! = Null) {www.2cto.com
M. setFromIp (fromIp );
MessageProcessor. processMessage (m); // submit it to the processor for processing.
Return;
}
Log. w (TAG, "Unresolved Message: from" + fromIp + "Data:" + Arrays. toString (msgPackage ));
}

Author: duancanmeng

Related Article

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.