XMPP Introduction Three: Socket

Source: Internet
Author: User
I record technology video address: https://edu.csdn.net/lecturer/1899 Welcome to watch.
One, what is the socket socket essentially provides the endpoint of the process communication. Before a process communicates, both parties must first create an endpoint, otherwise there is no way to establish a connection and communicate with each other. Just like before the phone call, both sides must each have a telephone. In the intranet, each socket is described in a half correlation: (protocol, local address, local port). A complete socket has a local unique socket number, which is allocated by the operating system. Most importantly, the socket is designed for client/server models and provides different socket system calls for client and server programs. Customers randomly apply for a socket (equivalent to a person who wants to call can dial a call on any network phone), the system assigns a socket number, the server has a globally recognized socket, Any customer can send it a connection request and a request for information (equivalent to a called phone with a phone number known to the caller). The socket uses client/server mode to skillfully resolve the problem of establishing a communication connection between processes. It is important that server sockets are partially related to the global. Readers may wish to consider how to establish communication between two completely random user processes. If the two sides of the communication do not have either side of the socket fixed, it is like the two sides of the phone do not know each other's phone number, to call is impossible. Second, socket in the network between the role of the level

As can be seen from the diagram, the socket is a bridge between the application layer and the transport layer. Further analysis, the above image of the "Socket Abstraction layer" in the embodiment of iOS, the following figure:
Third, the socket workflow now we are positioned to the socket layer, to see its specific work flow.
1. The TCP server first creates a socket (calls the socket () method). 2. Bind a port number (call the Bind () method). 3. Turn on the listener (Invoke Listen () method). 4. Block until there is a client connection (calling the Accept () method). 5. When the client initiates the connection request (calls connect () method). 6. Assuming that the connection operation in step fifth completes, the client then sends the request and the server side (calls the Read () method). 7. The server-side reads the request information, handles the processing, and writes the results to the client (calling the Write () method). 8. After receiving the response data from the server, the client gets the data (called the Read () method). 9. When the end client wants to disconnect the connection request (call the Close () method). The fifth step of the subject, here is a typical "three-time handshake" operation, the flowchart is as follows:
Four, socket code implementation because the socket communication is between the client and the server, so we should first consider building servers, but we are here just for the simple implementation of its functions, so directly with Python to implement a simple server on it. The code is as follows:
From Twisted.internet.protocol import protocol, Factory from twisted.internet Import reactor class Iphonechat (protocol): def connectionmade (self): #self. Transport.write ("" Connected "" ") Self.factory.clients.append (self) Print clients Are ", Self.factory.clients def connectionlost (self, Reason): Self.factory.clients.remove (self) def datareceive
			
			D (Self, data): #print "Data is", data A = Data.split (': ') If Len (a) > 1:command = a[0] content = a[1] msg = "" if command = = "Iam": self.name = Content msg = Self.name + "has joined" elif command = 
				
	= "MSG": Msg = self.name + ":" + content print msg for C in Self.factory.clients:c.message (msg) Def message (self, message): Self.transport.write (message + ' \ n ') factory = Factory () Factory.protocol = Iphonec Hat factory.clients = [] reactor.listentcp (12345, Factory) print "Iphone Chat server Started" Reactor.run ()

Code Description: Because we are here to implement the socket level of communication, so we need to consider a few points: 1. The port number of the server. 2. The contract of communication (that is, what data the client sends over, the server can identify). In the above code, we can see: 1. The port number of the service socket we defined is 12345. 2. The Communication contract format we define is separated by a "colon". "Iam:xxx" means the landing contract, "msg:xxx" means the chat contract. And then we can start this service:
After processing the service side, we started to start the client code:
VIEWCONTROLLER.M//a01_ chat room////Created by Lifei on 15-12-24. Copyright (c) 2015 Apple.
All rights reserved. #import "ViewController.h" @interface Viewcontroller () <nsstreamdelegate,uitableviewdatasource,
    uitableviewdelegate,uitextfielddelegate>{Nsinputstream *_inputstream;
Nsoutputstream *_outputsteam;
@property (Weak, nonatomic) Iboutlet UITableView *tableview;
@property (Weak, nonatomic) Iboutlet nslayoutconstraint *bottomconstraint;
/** * Stores all chat data arrays/@property (strong, nonatomic) Nsmutablearray *msgs; @end @implementation Viewcontroller #pragma mark-init relative-(Nsmutablearray *) msgs {if (!_msgs) {_
    Msgs = [Nsmutablearray array];
return _msgs;

}-(void) Dealloc {[[Nsnotificationcenter defaultcenter] removeobserver:self];}
    -(void) viewdidload {[Super viewdidload];
    
    Do no additional setup after loading the view, typically from a nib. [[Nsnotificationcenter Defaultcenter] AddobServer:self selector: @selector (kbwillshow:) name:uikeyboardwillshownotification Object:nil]; [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (kbwillhide:) Name:
Uikeyboardwillhidenotification Object:nil]; 
    
    #pragma mark-keyboard notifications-(void) Kbwillshow: (nsnotification *) notification {//show change Bottomcontraint
    CGFloat kbheight = [Notification.userinfo[uikeyboardframeenduserinfokey] cgrectvalue].size.height;
Self.bottomConstraint.constant = Kbheight;

}-(void) Kbwillhide: (nsnotification *) Notification {self.bottomConstraint.constant = 0;}
    #pragma mark-events-(ibaction) Connecttoserver: (ID) Sender {//ios to implement the connection Sokcet, using C//1. Connect with the server through three handshake
    NSString *host = @ "127.0.0.1";
    
    int port = 12345;
    2. Define the input output stream cfreadstreamref Readstream;
    
    Cfwritestreamref Writestream; 3. Allocate the input output stream memory space Cfstreamcreatepairwithsockettohost (NULL, (__bridge cfstringref) host, Port, &readstream, &amP;writestream);
    4. Transfer the input and output of C language into OC object _inputstream = (__bridge Nsinputstream *) (Readstream);
    
    _outputsteam = (__bridge Nsoutputstream *) (Writestream);
    5. Set up the agent to monitor the status of the data received _outputsteam.delegate = self;
    
    _inputstream.delegate = self; Add input stream to main run loop (RUNLOOP)//main run loop is listening to network status [_outputsteam scheduleinrunloop:[nsrunloop Mainrunloop] Formode:nsdefau
    Ltrunloopmode];
    
    
    [_inputstream Scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];
    6. Open the input output stream [_inputstream open];
[_outputsteam Open]; }-(Ibaction) Loginbtnclick: (ID) Sender {//Send login request using output stream//Stitching login Instructions Iam:zhangsan nsstring *loginstr = @ "ia
    
    M:zhangsan ";
[Self senddatatohost:loginstr]; #pragma mark-public Methods-(void) Senddatatohost: (NSString *) str {//uint8_t * character array nsdata *data = [str dat
    Ausingencoding:nsutf8stringencoding];
[_outputsteam write:data.bytes maxLength:data.length];
    }-(void) ReadData {
    Define buffer This buffer can only store 1024 bytes uint8_t buf[1024];
    
    Read Data//Len the actual number of bytes read to the server Nsinteger len = [_inputstream read:buf maxlength:sizeof (BUF)]; Turns the implementation byte number in the buffer into a string nsstring *receiverstr = [[NSString alloc] Initwithbytes:buf length:len Encoding:nsutf8stringencodi
    NG];
    
    NSLog (@ "%@", receiverstr);
    
    Add the data to the msgs array [self.msgs ADDOBJECT:RECEIVERSTR];
Refresh table [Self.tableview Reloaddata]; #pragma mark-nsstreamdelegate-(void) stream: (Nsstream *) Astream handleevent: (nsstreamevent) EventCode {//proxy callbacks are in the main
Thread NSLog (@ "%@", [Nsthread CurrentThread]); nsstreameventopencompleted = 1UL << 0,//nsstreameventhasbytesavailable = 1UL << 1,//NSSTREAMEV enthasspaceavailable = 1UL << 2,//nsstreameventerroroccurred = 1UL << 3,//Nsstreameventendencountere D = 1UL << 4 switch (eventcode) {case Nsstreameventopencompleted:nslog (@ "%@", Astream)
            ; NSLog (@ "Successful connection established")To form a transmission channel of the input-output stream ");
            
        Break
            Case Nsstreameventhasbytesavailable:nslog (@ "have data readable");
            [Self readdata];
            
        Break
            Case Nsstreameventhasspaceavailable:nslog (@ "can send data");
            
         Break
            Case Nsstreameventerroroccurred:nslog (@ "error occurred, Connection failed");
            
         Break
            Case Nsstreameventendencountered:nslog (@ "normal disconnect");
            Turn off the input stream and remove [_inputstream close] from the main run loop;
            [_outputsteam Close];
            [_inputstream Removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];
            [_outputsteam Removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];
        Break
    Default:break; }} #pragma mark-uitableviewdelegate/datasource-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection :(Nsinteger) Section {return Self.msgs.counT }-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath {static NSS
    Tring *id = @ "Chatcell";
    UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:id];
    Cell.textLabel.text = Self.msgs[indexpath.row];
return cell;

}-(void) scrollviewwillbegindragging: (Uiscrollview *) ScrollView {[Self.view endediting:yes];}
    #pragma mark-textfielddelegate-(BOOL) Textfieldshouldreturn: (Uitextfield *) TextField {//Send chat Data//1. Data is sent
    
    NSString *txt = Textfield.text;
    
    if (txt.length = 0) return YES;
    Send data NSString *msg = [@ ' msg: ' stringbyappendingstring:txt];
    
    [Self senddatatohost:msg];
return YES;
 } @end

Code, I have made a detailed comment. Its basic function is that the client sends a message to the server, and the server side prints out the information (at the terminal). After the server has processed the data, it will return the information to the client, and the client will refresh the table and show the chat data after receiving the information. The final effect figure is as follows:

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.