You know, there are these classic licensing agreements and frameworks in iOS, so how do they implement our chat?

1) Socket-native: represents the framework CocoaAsyncSocket.

2) Based on WebScoket: stands for SocketRocket framework.

3) Based on MQTT: represents the framework MQTTKit.

4) Based on XMPP: represents the framework XMPPFramework

First of all, MQTT and XMPP are chat protocols, which are the top layer protocols, while WebScoket is a transport protocol, which is a protocol based on Socket encapsulation. And usually we said Tencent IM private protocol, is based on WebScoket or Scoket native encapsulation of a chat protocol.

So first of all, let’s simulate the socket encapsulation protocol to achieve communication.

Node builds local services and socket implements communication protocols

1. Make sure you have the Node interpreter installed on your MAC, then create a server.js file and run the script to start the local server configuration

Here is the implementation code for our configuration file

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 3308;
net.createServer(function(sock) {
    console.log('CONNECTED: ' +
        sock.remoteAddress + ':' + sock.remotePort);
        sock.write('Server issued: Connection successful');
    sock.on('data'.function(data) {
        console.log('DATA ' + sock.remoteAddress + ':' + data);
        sock.write('You said "' + data + '"');
    });
    sock.on('close'.function(data) {
        console.log('CLOSED: ' +
        sock.remoteAddress + ' ' + sock.remotePort);
    });
  }).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
Copy the code

Nodeserver.js starts with the server listening on 127.0.0.1:3308

2. Then we implement the chat protocol of socket on the client

TYHSocketManager.h @interface TYHSocketManager : NSObject +(instancetype)share; - (void)connect; - (void)disConnect; - (void)sendMsg:(NSString *)msg;
 
@end
Copy the code
TYHSocketManager.m

#import "TYHSocketManager.h"

#import <sys/types.h>

#import <sys/socket.h>

#import <netinet/in.h>

#import <arpa/inet.h>

@interface TYHSocketManager()

@property (nonatomic, assign) int clientSocket;

@end

@implementation TYHSocketManager

+ (instancetype)share {
    static dispatch_once_t onceToken;
    static TYHSocketManager *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}

- (void)initSocket {
   ` `if(_clientSocket ! =0) {
    
        [self disConnect];
        _clientSocket = 0;
    }
    // Create client socket
    _clientSocket = CreateClinetSocket();
    // Server IP address
    // Server Ip address
       const char * server_ip="127.0.0.1";
       // Server port
       short server_port= 3308;
       // If the value is 0, the connection fails
       if (ConnectionToServer(_clientSocket,server_ip, server_port)==0) {
           printf("Connect to server error");
           return ;
       }
       // The connection is successful
      printf("Connect to server ok");` `
}

static int CreateClinetSocket()
{
    int ClinetSocket = 0;
    // Create a socket with the return value Int. (Note that a scoket is an Int)
    AddressFamily IPv4(AF_INET) or IPv6(AF_INET6).
    // The second parameter type indicates the socket type, usually a stream(SOCK_STREAM) or datagram(SOCK_DGRAM).
    // The third parameter protocol is usually set to 0, so that the system automatically selects the appropriate protocol for us. For stream sockets, this is IPPROTO_TCP. For Datagram it would be IPPROTO_UDP.
    ClinetSocket = socket(AF_INET, SOCK_STREAM, 0);
    return ClinetSocket;
}
static int ConnectionToServer(int client_socket,const char * server_ip,unsigned short port)
{

    // Generate a sockaddr_in structure
    struct sockaddr_in sAddr={0};
    sAddr.sin_len=sizeof(sAddr);
    / / set the IPv4
    sAddr.sin_family=AF_INET;

    //inet_aton is an improved method of converting a string IP address into a 32-bit network sequence IP address
    // The function returns a non-zero value if it succeeds, or zero if the input address is incorrect.
    inet_aton(server_ip, &sAddr.sin_addr);

    //htons converts integer variables from host byte order to network byte order, assigning port numbers
    sAddr.sin_port=htons(port);

    // initiate a connection with a server address and a scoket.
    // The client sends a connection request to the server at a specific network address. 0 is returned on success and -1 is returned on failure.
    // Note: This interface call blocks the current thread until the server returns.
    if (connect(client_socket, (struct sockaddr *)&sAddr, sizeof(sAddr))==0) {
        return client_socket;
    }
    return 0; } #pragma mark -- new threads receive messages -- (void)pullMsg { NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(recieveAction) object:nil]; [thread start]; } #pragma mark - (void)connect {
    [self initSocket];
}

- (void)disConnect {
    close(self.clientSocket);
}

- (void)sendMsg:(NSString *)msg {
    const char *send_Message = [msg UTF8String];
    send(self.clientSocket, send_Message, strlen(send_Message)+ 1.0);
}

// Receive messages sent by the server
- (void)recieveAction{
    while (1) {
        char recv_Message[1024] = {0};
        recv(self.clientSocket, recv_Message, sizeof(recv_Message), 0);
        printf("%s",recv_Message);
    }
}
@end
Copy the code

And the final result is this

We initiate a connection on the client, and then send a message, which can be received on the terminal (note: if the requested port is occupied, please kill or apply for another).

XMPP and OpenFire implement local service communication

1. We first need to download and install locally and set up the database, in this I refer to is www.jianshu.com/p/f06ba0ea7… Sudo su: /usr/local/openfire/bin: /usr/local/openfire/bin: /usr/local/openfire/bin However, by the time we need to open the server’s Open Admin Console configuration, there are always some minor problems and we can’t proceed, so don’t lose this step.

2. If all of the above is implemented, then we can see some server-related data and user group information in the OpenFire background.

3. At first, I downloaded Adium and Spark according to the processing method of the reference link, and the configuration can realize communication

4. But our ultimate goal is to write their own app to communicate, so I on the basis of continue development, reference XMPP protocol framework, realize the communication between the app and spark, it is also a reference to the case, some online actually arrived at this time we are clear, the next is to implement custom page chat!