Instant Messaging-related understanding of iOS

Source: Internet
Author: User

Socket:

1>socket also known as "sockets"

The two programs on the 2> network enable the exchange of data through a two-way communication connection, one end of the connection being called a socket.

3> applications typically make requests to the network via "sockets" or respond to network requests Elements of network communication:A request on the 1> network is to establish a connection through a socket and then communicate with each other 2>IP address (a unique identifier of the host device on the network) 3> port number (Locator) 4> the logical address used to indicate the process, the identification of the different processes 5> the active port: 0~ 65535, where 0~1024 is used by the system or reserved ports, the development of the recommended use of more than 1024 ports 6> transport protocol (how to interact with) the rules of Communication: Common protocol: TCP, UDP TCP&UDP:TCP (Transmission Control Protocol) 1> establish a connection to form a channel for transmitting data 2> large data transfer in connection (unlimited) 3> through three handshake to complete the connection, is a reliable protocol, secure delivery 4> must establish a connection, the efficiency will be slightly lower

UDP (User Datagram Protocol)

1> data and source and destination into a packet, do not need to establish a connection 2> each datagram size limit within 64K 3> because there is no need to connect, it is unreliable protocol 4> do not need to establish a connection, fast Socket Communication Flowchart:

1.HTTP the bottom is the connection through the socket to establish a communication pipeline to achieve data transmission

2.HTTP is a TCP Transport protocol (mode), it is a reliable, secure protocol

To implement the socket service-side monitoring:Implementation of the Socket monitoring method (1) using the C language implementation, (2) Using Cocoaasyncsocket third box, internal is the encapsulation of C telnet command telnet host port/telnet 192.168.10.10 The 5288telnet command is a service that corresponds to a port on the connection server Forwarding Message service:Multiple clients connect to the server when a client sends a message server, the server forwards to the other connected clients. The equivalent of a group chat. protocol on the socket layer:Protocol on the socket layer refers to the format of the data transfer 1>http protocol

Transport format: Suppose: This is the assumption that the actual HTTP format is not the case.

http1.1,content-type:multipart/form-data,content-length:188,body:username=zhangsan&password=123456

XMPP protocol, an Instant messaging protocol

Extensible Message Processing Field Protocol) is an Extensible Markup Language (XML)-based protocol that is used for instant messaging (IM) and on-line on-site probing. This agreement may eventually allow Internet users to send instant messages to anyone else on the internet

Transfer format:

<from>zhangsan<from>

<to>lisi<to>

<body> eat together at night </body>

2> Custom Instant Messaging protocol, JSON format

{

"From": "Zhangsan",

"To": "Lisi",

"Body": "Eat Lunch Together"

}

Instant Messaging: Instant messaging, also known as real-time communication

Instant Messaging (Instant Messaging, abbreviated IM) is a real-time communication system that allows two or more people to use the network real-time transmission of text messages, files, voice and video communication in the development of the scene used in the development of a type, QQ, Forex's chat software integrates the real-time communication between buyers and sellers in e-commerce app, and realizes the Instant Messaging scenario 1. XMPP2. Huan Xin What is XMPP:(1) Xmpp:the extensible Messaging and Presence Protocol (extensible Communication and Presentation Protocol) (2) XMPP is an XML-based Instant Messaging protocol, and the official documentation for XMPP is RFC 3920, which defines the login, exit , get friends, send messages, and so on XML data Transfer Protocol (3) XMPP is a typical C/s architecture, the basic network form is that the client connects to the server via TCP/IP, establishes the connection through the socket, and then transmits the XML stream on top (4) XMPP is a kind of data transmission protocol similar to the HTTP protocol, its process is like "unpack--〉 packaging" process. It is necessary to understand the type of receiving and the type of return, and can use XMPP for data communication (5) XMPP official website--http://xmpp.org XMPP enables instant communication readiness:1> download OpenFire server 2> Download Xmppframework framework Ring Letter:The ring letter is a third platform that provides instant messaging (im–instant Messaging) service ring letter is on the basis of XMPP two times to develop the data transmitted on the network of the ring letter is also XML using the ring letter, do not set up their own server, save the cost of the ring letter 300,000 less than the day, Forever Free Company to develop instant messaging software, recommended preferred ring letter, the market share of the ring is larger prerequisites for integrating the ring letter:1> registered as a http://www.easemob.com2> developer to create an app in the developer background key3> download the official SDK demohttp://www.easemob.com/docs/ios/ Iossdkprepare/Integration SDK Step:1> based on the official website Import SDK and corresponding dependent 2> initialization application, there are two methods
/**registersdkwithappkey: Differentiate the app's logo, developer registration and management background Apnscertname:ios the name of the push certificate. Create and upload a push certificate *///the initialization of the Ring letter//    [[Easemob sharedinstance] registersdkwithappkey:@ "Vgios#hxchat" apnscertname:@ ""];    Initialization of the ring and hiding the log output    [[Easemob sharedinstance] registersdkwithappkey:@ "Vgios#hxchat" apnscertname:@ "otherconfig:@ {ksdkconfigenableconsolelogger:@ (NO)}];

Ring Login:

Registered:

[[Easemob Sharedinstance].chatmanager Asyncregisternewaccount: "vgios1" Password: "123456" withcompletion:^ (NSString  *username, NSString *password, Emerror *error) {        NSLog (@ "error:%@ username:%@ pwd:%@", Error,username,password);    } Onqueue:nil];

Automatic Login:

Automatic login: Of course, when the program starts again, if the user has successfully logged in, do not need to enter the user name and password to login implementation method (1) The login account information is saved, the program starts to send the login request (2) The ring letter has been implemented automatic login, only need to call the following method after the first successful login
[[Easemob Sharedinstance].chatmanager Setisautologinenabled:yes]; Summary: Either way, the essence is to call the logon network request again Automatic connection:If the network does not pass, the user should automatically connect to the server to receive messages in a timely manner without the programmer's own, the ring-letter framework has been implemented, the Ring letter SDK will call the automatic connection agent method to notify the application
/*! @method @brief Send this callback when an automatic re-connect operation is to be initiated @discussion @result */-(void) willautoreconnect; /*! @method @brief The callback after the auto-re-connect operation is complete (success, nil, failure, viewing error message) @discussion @result */-(void) Didautoreconnectfinishedwitherror: (Nserror *) error;

Emchatmanagerbuddydelegate:

The above protocol implements the basic operation of the user, such as (1) Add Friend (2) from the Local Get Friends List (3) Get the latest friend list from the server (4) Receive friend Add request (5) Delete friend (6) deleted by friends from the list text send:

The process of sending a ring letter message

1. Save the record to the conversation table first

2. Then send the network request, the API is as follows

[[Easemob Sharedinstance].chatmanager asyncsendmessage:message progress:self prepare:^ (EMMessage *message, EMError * Error) {        Kslog (@ "Prepare%@", message.messagebodies);    } onqueue:nil completion:^ (emmessage *message, Emerror * Error) {        Kslog (@ "Completed%@", message.messagebodies);    } Onqueue:nil];

To display a chat message:

Step ① First Get Emconversation Session Manager Object ② call Emconversation-(Nsarray *) Loadnumbersofmessages: (Nsuinteger) acount before: (Long Long) timestamp; Gets the specified chat record to listen to a friend's reply message: The current chat page, listen to the timely message sent by friends to get history and unread messages: ring-Letter provides session manager (Emconversation) to manage the number of unread messages and history chat records, The specific code below is the total number of unread messages that need to traverse conversations
1. Get all historical sessions   nsarray *conversations = [[Easemob sharedinstance].chatmanager conversations];        2. If there is no session in memory, load the    if (Conversations.count = = 0) from the database {        conversations = [[Easemob Sharedinstance].chatmanager Loadallconversationsfromdatabasewithappend2chat:yes];    }

Set message as read:

When you enter the chat page, you need to set all current session information or set a message that has already been loaded as read
Set current session All messages are read [self.conversation markallmessagesasread:yes];//set a message as read [Self.conversation Markmessagewithid: <# (NSString *) #> asread:<# (BOOL) #>]

Preparatory work:

Before recording, import the two recording frames in the ring envelope, Implementing Recordings:The two frames that have just been imported have implemented the recording API
Start recording    [[Emcddevicemanager sharedinstance] asyncstartrecordingwithfilename:filename  completion:^ (NSError *error) {         if (error) {             Kslog (@ "Failure to start recording");         }     ];    End recording    [[Emcddevicemanager sharedinstance] asyncstoprecordingwithcompletion:^ (nsstring *recordpath, NSInteger Aduration, Nserror *error) {        kslog (@ "%@", Recordpath);    }];

Send recording:

Voice object    Emchatvoice *voice = [[Emchatvoice alloc] initwithfile:filepath displayname:@ "audio"];        Message body    Emvoicemessagebody *body = [[Emvoicemessagebody alloc] initwithchatobject:voice]; Emmessage *message = [[Emmessage alloc] initWithReceiver:self.buddy.username Bodies:@[body]];    Message.messagetype = emessagetypechat;//Private chat    //unencrypted    message.requireencryption = no;

To play a recording:

[[Emcddevicemanager sharedinstance] Asyncplayingwithpath:filepath completion:^ (nserror *error) {    NSLog (@ "Play completed%@", error);            }];
exit (Async method):
[[Easemob Sharedinstance].chatmanager asynclogoffwithunbinddevicetoken:yes completion:^ (NSDictionary *info, EMError *error) {  if (!error) {//exit succeeded  }else{//exit failed;  }} Onqueue:nil];

is the implementation principle of using XMPP,XMPP:

XMPP is an Instant messaging protocol that regulates the format of data transfer formats for Instant messaging on the network, such as logging in, getting a list of friends, and so on. The data that XMPP transmits on the network is XML format such as login: Put username and password in XML tag, transfer to server XMPP is a network protocol based on socket, which is to save long connection, To enable Instant Messaging the client of XMPP is using a xmppframework framework to implement XMPP's server is using OpenFire, an open source server client obtains a friend message sent over to the server, the client needs to parse the XML, Use the Kissxml framework of the parsing framework, rather than nsxmlparser/gdataxml There is no difficulty in using XMPP:Send attachments (Pictures, voice, documents ...) ) when the XMPP framework does not provide the ability to send attachments, you need to implement the implementation method, upload the file to the file server, get the file save path after successful uploading, and then send the attachment path to the friend whether to use the ring letter, simple to say the principle of the implementation of the Ring letter:Ring Letter is an instant messaging service provider that uses the XMPP protocol, which is based on two development on the basis of the XMPP, the addition of the functional model to the server OpenFire and the client and the encapsulation of the client SDK, the nature of the ring letter or the use of XMPP, The basic socket network communication Ring letter internal implementation of the data cache, will add chat records to the database, attachments (such as audio files, picture files) to download to the local, so that the programmer more time is spent on the user's instant experience on the inside of the ring letter has realized the video, audio, pictures, Other accessories send function ring letter using the company can save time costs do not need to build the internal server client development, using the Ring letter SDK than the use of xmppframework more concise and convenient

Instant Messaging-related understanding of iOS

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.