Socket:

1>Socket also called " Socket ”

2> Two programs on the network exchange data through a two-way communication connection , One end of this connection is called a socket.

3> Applications usually go through " Socket " Send a request to the network or answer a network request
 
The elements of network communication :
1> Requests on the Internet are made through Socket To establish a connection and communicate with each other
2>IP Address ( Unique identification of the host device on the network )
3> Port number ( Location program )
4> The logical address used to identify the process , Identification of different processes
5> Valid port :0~65535, among 0~1024 Used or reserved by the system , It is recommended to use 1024 Ports above
6> Transfer protocol ( How to interact ) The rules of communication :  Common agreements :TCP、UDP
 
TCP&UDP:
TCP( Transmission control protocol )
1> Establishing a connection , To form a channel for data transmission
2> Big data transfer in connection ( Unlimited data )
3> Connect through three handshakes , It's a reliable agreement , Safe delivery
4> Connection must be established , It's a little less efficient

UDP( User datagram protocol )

1> Encapsulate data, source and destination into packets , No connection needed
2> The size of each datagram is limited to 64K within
3> Because there's no need to connect , So it's an unreliable protocol
4> No connection needed , Fast
 
Socket Communication flow chart :

1.HTTP The bottom floor is through socket Set up a communication pipeline , Realize data transmission

2.HTTP It's a TCP Transport protocol ( The way ), It's a reliable , A secure agreement

 
Realization Socket Server monitoring :
Realization socket How to monitor
(1) Use C Language implementation ,
(2) Use CocoaAsyncSocket Box 3 , Inside is right C Encapsulation
Telnet command telnet host port/telnet 192.168.10.10 5288
telnet A command is to connect to a service corresponding to a port on the server
 
Forward message service :
Multiple clients connect to the server
When a client sends a message to the server , The server forwards it to other connected clients .
It's like a prototype of group chat
 
Socket Protocol on layer :
Socket Protocol on layer refers to the format of data transmission
1>HTTP agreement

Transmission format : hypothesis : It's a hypothesis , actual http This is not the format of .

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

XMPP agreement , It's an instant messaging protocol

Extensible message processing field protocol ) It's based on extensible markup language (XML) The agreement , It's used for instant messaging (IM) And online live detection . This protocol may eventually allow Internet users to send instant messages to anyone else on the Internet

Transmission format :

<from>zhangsan<from>

<to>lisi<to>

<body> Have dinner together. At night </body>

2> Custom instant messaging protocol ,json Format

{

“from”:”zhangsan”,

”to”:”lisi”,

”body”:” Lunch together ”

}

im : im , Also known as real-time communication

Instant messaging (Instant Messaging, abbreviation IM) It's a real-time communication system , Allow two or more people to use the network to deliver text messages in real time 、 file 、 Voice and video communication
The scenarios used in the development of instant messaging
Develop a type of wechat ,QQ, Eason's chat software
In the electricity supplier APP Integrate real-time communication between buyers and sellers, etc
At the moment , Instant messaging solutions
1.XMPP
2. Ring letter
 
XMPP What is it? :
(1)XMPP:The Extensible Messaging and Presence Protocol( Scalable communication and presentation protocols )
(2)XMPP It's based on XML Instant messaging protocol for ,XMPP The official document of is RFC 3920
  This document defines the login , sign out , Get friends , Sending messages and so on XML Data transfer protocol
(3)XMPP It's a typical C/S framework , The basic form of network is the client through TCP/IP Connect to the server , adopt Socket Establishing a connection , And then transmit it over XML flow
(4)XMPP It's something like HTTP A kind of data transmission protocol of protocol , The process is like “ Unpack --〉 packing ” The process of . Just understand the type it receives and the type it returns , Then you can make good use of XMPP For data communication
(5)XMPP Official website —— http://xmpp.org
 
XMPP Preparations for instant messaging :
1> download Openfire The server
2> download XMPPFramework frame
 
Ring letter :
Huanxin is a third platform , Provide instant messaging (IM –Instant Messaging ) Service for
Huanxin is in XMPP On the basis of the second development
The data transmitted by Huanxin on the network is also XML
Use ring letter , You don't have to build your own server , Cost savings
Huanxin rihuo 30 All of the following , Always free
If a company wants to develop instant messaging software , It is suggested that the first choice is Huanxin , Huanxin has a large market share
 
The prerequisite preparation of integrated environmental information :
1> Sign up as a developer of Huanxin
http://www.easemob.com
2> Create... In the developer's background APP obtain Key
3> Download the official SDK DEMO
http://www.easemob.com/docs/ios/IOSSDKPrepare/
 
Integrate SDK step :
1> According to the official website SDK And corresponding dependencies
2> Initialize application , There are two ways
/*
*registerSDKWithAppKey: difference app The logo of , Developer registration and management background
apnsCertName: iOS Push certificate name in . Making and uploading push certificates
*/
// Initialization of ring message
// [[EaseMob sharedInstance] registerSDKWithAppKey:@"vgios#hxchat" apnsCertName:@””]; // Initialization of ring message And hide the log output
[[EaseMob sharedInstance] registerSDKWithAppKey:@"vgios#hxchat" apnsCertName:@"" otherConfig:@{kSDKConfigEnableConsoleLogger:@(NO)}];

Ring letter login :

register :

[[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:”vgios1” password:”123456” withCompletion:^(NSString *username, NSString *password, EMError *error) {
NSLog(@"error:%@ username:%@ pwd:%@",error,username,password);
} onQueue:nil];

automatic logon :

automatic logon : Of course, when the program starts again , If the user has successfully logged in , There is no need for users to enter a user name and password to log in
Implementation method
(1) Save the login account information , The program starts to send a login request
(2) Huanxin has realized automatic login , It only needs to be called after the first login The following method is enough
[[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
summary : Either way , The essence is to call the login network request again
 
Auto connect :
If the network doesn't go through , Users should automatically connect to the server , Receive messages in time
This feature doesn't need to be done by the programmer himself , The framework has been implemented , Ring letter SDK The proxy method of automatic connection is called to inform the application
/*!
@method
@brief The callback is sent when the automatic reconnection operation is about to be initiated
@discussion
@result
*/
- (void)willAutoReconnect; /*!
@method
@brief Callback after automatic reconnection operation is completed ( If you succeed ,error by nil, Failure words , see error Error messages for )
@discussion
@result
*/
- (void)didAutoReconnectFinishedWithError:(NSError *)error;

EMChatManagerBuddyDelegate:

The above protocol implements the basic operation of the user , Such as
(1) Add buddy
(2) Get friends list from local
(3) Get the latest friends list from the server
(4) Receive friend add request
(5) Delete friends
(6) Removed from the list by friends
 
Text send :

The process of sending ring message

1. First save the record to Conversation surface

2. Then send the network request ,API 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];

Show chat messages :

step
① First get EMConversation Session manager object
② call EMConversation Of - (NSArray *)loadNumbersOfMessages:(NSUInteger)aCount before:(long long)timestamp; Get the specified chat record
 
Listen to your friend's reply :
The current chat page , Listen to instant messages from friends
 
Get history and unread messages :
Huanxin provides session manager (EMConversation) To manage the number of unread messages and historical chats , The specific code is as follows
The total number of unread messages needs to be traversed conversations
// 1. Get all historical conversations 
NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations]; // 2. If in memory , There is no conversation , Load from database
if (conversations.count == 0) {
conversations = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
}

Set the message to read :

When you enter the chat page , You need to set all the current session information or set the loaded messages to read
//  Set all messages in the current session to read 
[self.conversation markAllMessagesAsRead:YES]; // Set a message to read
[self.conversation markMessageWithId:<#(NSString *)#> asRead:<#(BOOL)#>]

preparation :

Before recording, import two recording frames encapsulated by Huanxin , Pictured
 
Realize recording :
The two frameworks just imported , Recording has been realized API
//  Start the recording 
[[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error){
if (error) {
KSLog( @"failure to start recording");
}
}]; // End of the tape
[[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
KSLog(@"%@",recordPath);
}];

Send the 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;// The private chat
// No encryption
message.requireEncryption = NO;

Play the recording :

[[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:filePath completion:^(NSError *error) {
NSLog(@" The playback is finished %@",error);
}];
 
sign out ( Asynchronous methods ):
[[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES completion:^(NSDictionary *info, EMError *error) {
if (!error) {// Quit successfully
}else{// Exit failed ;
}
} onQueue:nil];

Have you ever used XMPP,XMPP Implementation principle of :

XMPP It's an instant messaging protocol , It standardizes the data transmission format for instant messaging over the network , For example, login. , Get the format of friends list and so on .XMPP The data transmitted over the network is XML Format
For example, login. : Put your user name and password in xml Label , Transfer to server
XMPP It's one based on Socket Through the network protocol , The purpose is to save long connections , For instant messaging
XMPP The client is using a XMPPFramework Framework implementations
XMPP Our server is using Openfire, An open source server
The client gets the friend message sent by the server , The client needs to XML To analyze , The parsing framework used KissXML frame , instead of NSXMLParser/GDataXML
 
 
In the use of XMPP Do you need any difficulties when you are young :
Sending attachments ( picture , voice , file …) It's more troublesome
XMPP The framework does not provide the ability to send attachments , You have to implement it yourself
Implementation method , Upload the file to the file server , After the upload is successful, obtain the file save path , Then send the path of the attachment to friends
 
 
Has ring letter been used , Simply speaking, the realization principle of the lower ring signal :
Huanxin is an instant messaging service provider
Ring letter uses XMPP agreement , It is again XMPP On the basis of the second development , To the server Openfire Add function model and client with client SDK Encapsulation , The essence of ring letter is to use XMPP, Basically Socket Network communication
The data cache is implemented inside the ring letter , Will add chat records to the database , Put the accessories ( Such as audio files , Picture file ) Download to local , Making programmers spend more time on the user's immediate experience
Video has been realized in Huanxin , Audio , picture , Other attachment sending functions
The company can save time and cost
No need to build servers inside the company
Client development , Use ring letter SDK Than using XMPPFramework It's simpler and more convenient

iOS Instant messaging related to the understanding of more related articles

  1. iOS - IM im

    1. Instant messaging technology im (IM:Instant Messaging): Also known as real-time communication , Support users to talk online in real time , Allow two or more people to use the network to deliver text messages in real time . file . Voice and video communication . The scenarios used in the development of instant messaging ...

  2. iOS Development -- Instant messaging often uses third-party libraries

    Preface From graduation to now , be engaged in iOS Instant messaging development has 1 Years and a half . Mainly responsible for Allure Development , It's on the shelves now , You can search for vegetables in the apple store Allure.Allure Imitate the interaction and design effect of wechat , Most of the functions of wechat have been realized . ad locum ...

  3. iOS Development -- im

    What is ring letter ? 1. Huanxin is a third platform , Provide instant messaging (IM–Instant Messaging ) Service for 2. Huanxin is in XMPP On the basis of the second development 3. The data transmitted by Huanxin on the network is also XML 4. Use ring letter , No ...

  4. xmpp Instant messaging notes ( Extract )

    xmpp Use : im  instant messaging(IM) :  --> Send and receive information in real time ! Instant messaging software : **QQ,MSN,GoogleTalk,AIM,Jabber(XMPP Alias ...

  5. Openfire XMPP Smack RTC IM im Chat MD

    Markdown Version notes my GitHub home page My blog My WeChat My mailbox MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  6. 【 original 】 Lightweight mobile instant messaging technology MobileIMSDK Released

    Affirming :MobileIMSDK At present, it is an individual original open source project , Invested a lot of time and energy , I hope it can help people in need . If you need to communicate with the author , See personal signature at the bottom of the article , learn from each other .Q Group :215891622, Welcome to study and exchange with people with common interests . ...

  7. openfire+smack Implement the basic framework of instant messaging

    smack jar Download address  http://www.igniterealtime.org/downloads/download-landing.jsp?file=smack/smack_3_2_2.zi ...

  8. of IM Instant messaging principle

    I searched the Internet for some information , Talk about how you feel about IM The understanding of instant messaging IM Its full name is Instant Messaging, im , Such as qq That kind of . Now there are two users UserA, UserB, The two are one IM Friends of communication software ,Us ...

  9. iOS im , From the beginning to “ give up ”?

    Link to the original text :http://www.jianshu.com/p/2dbb360886a8 In this article, we will use examples , take iOS Various IM All of the solutions are implemented simply . And provide some selection . Implementation details and optimization suggestions . — ...

Random recommendation

  1. Kendo UI for ASP.NET MVC Some use experience of ( turn )

    from  http://blog.csdn.net/dj2008/article/details/45313805 In recent projects Kendo UI. It's very good and powerful , Unfortunately, the official documents are not well organized , There are ...

  2. C Programming style of human-computer interaction -- CSHELL ( Provide source code download )

    Remember when I was in College , do C Language programs use sdb To debug : And then there was gdb, Same as sdb almost , But it's easy to use . But it's a little bit of a pity after all . such as , Several functions are designed in the program , If you want to test them , You have to write another test function , Use all kinds of ...

  3. Talk about it google Of Knowledge Graph

    What is? Knowledge Graph? It is google A technology used to enhance the functionality of its search engine and improve the quality of search results . stay 2012 year 5 month 16 Proposed by Japan , In addition to providing basic link services related to topics , It can also be structured to match the theme ...

  4. Even if it's connected ping It will also fail

    /*************************************************************************** * Even if it's connected ping It will also fail * explain : * ...

  5. Oracle Execute script files in bulk

    Here are Oracle Steps and methods for batch execution of script files 1. Create script file (xx.sql): Such as files CreateTable Create table tb1( id varchar2(30), Name va ...

  6. 201521123101 《Java Programming 》 The first 5 Weekly learning summary

    1. This week's learning summary 2. Written work 1. Code reading :Child Code inside the package 1.1 com.parent In bag Child.java Can the file be compiled ? Which sentence will go wrong ? Try to correct the mistake . And analyze the output . You can't ...

  7. oracle erp Table structure

    BOM Module commonly used table structure Table name : bom.bom_bill_of_materials explain : BOM List parent items BILL_SEQUENCE_ID NUMBER List number ( keyword )ASSEMBLY_ITEM ...

  8. android DecorView In depth understanding of

    In development , It's usually in onCreate() Call in setContentView(R.layout.custom_layout) To achieve the desired page layout . Pages are attached to windows , and DecorView It's the top of the window ...

  9. dhtmlx Gantt Example introduction and analysis

    API Address :https://docs.dhtmlx.com/gantt/desktop__guides.html, This is the English web page , You can google it and translate it , It's in Chinese ! I use it DHTMLX Ga ...

  10. redis_ Simple dynamic string

    stay redis in ,C character string ( With '\0' Array of characters at the end ) Only in places where there is no need to modify string values , For example, printing logs . Other situations ,redis Use SDS - SimpleDynamicString Simple dynamic string , Come on ...