Instant Messaging-related understanding of iOS

Source: Internet
Author: User


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 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.


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:



<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 XMLDataTransport 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 a connection through the socket, and then transmits the XML stream (4) XMPP is a data transfer protocol similar to the HTTP protocol, and the process is like " The process of unpacking--〉 packaging ". 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-- 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 demo Integration SDK Steps: 1> based on the official website to import the SDK and the 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:@ ""];     // Initialize the ring and hide the log output    [[Easemob sharedinstance] Registersdkwithappkey:@ "vgios#hxchat" apnscertname: @ "" otherconfig:@{ksdkconfigenableconsolelogger:@ (NO)}];

Ring Login:


[[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
/* */-(void/*/-(void) Didautoreconnectfinishedwitherror: (Nserror *) error;


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 (@ " complete%@ " , 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 Listen to a friend's reply message: Current Chat page, listen to your friends to send timely messages Get history and unread message count: The Session Manager (Emconversation) is provided to manage the number of unread messages and historical chats, as follows the total number of unread messages that need to traverse conversations
// 1. Get all history sessions   Nsarray *conversations = [[Easemob sharedinstance].chatmanager conversations];         // 2. If there is no session in memory, load    from the database if 0 {        = [[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  Span style= "color: #800000;"         > " );    }     }];  //  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 =*message = [[Emmessage alloc] InitWithReceiver:self.buddy.username bodies:@ [body]];     = Emessagetypechat; // Private chat     // No encryption    Message.requireencryption = NO;

To play a recording:

[[Emcddevicemanager sharedinstance] Asyncplayingwithpath:filepath completion:^ (nserror *error) {    NSLog (  @ " play complete%@", 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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.