[IOS dry goods]☞Socket, socket for ios

Source: Internet
Author: User

[IOS dry goods]☞Socket, socket for ios
I. Concepts

  • Socket, also known as "Socket"

  • Two programs on the network (for example, the client and the server) exchange data through a two-way communication connection. one end of the connection is called a socket.

  • Generally, an application uses a Socket to establish a communication connection, and then sends a request to or responds to a network request.

  

Note:

☞Before a client sends a network request to the server, it must establish a communication connection (Communication Pipeline) at the underlying layer to send the network request.

The client sends an http request to the server and the server returns data. This process is a data exchange process.

To exchange data between the client and the server, you must first establish a two-way communication connection (that is, one line and one channel)

☞There is a Socket between the client and the server. A connection (two-way communication pipeline) is established through the Socket, and data transmission can be performed with the pipeline.

☞Socket is the two ports of the communication pipeline, which can be understood as the entrance/exit of the pipeline.

Ii. Elements of network communication

Requests on the network establish connections through sockets and then communicate with each other.

1. IP address (Unique Identifier of the host device on the network) --> find the server host

2. Port Number (positioning program) --> Find a program

3. Transmission Protocol (in what way to interact)

Iii. transmission protocol TCP/UDP

TCP and UDP: two methods of data transmission, namely, transmitting data from one end to the other

1. TCP (Transmission Control Protocol)-> establish a connection (for example, to send an HTTP request, the client sends a network request to the server)

☞Establish a connection to form a channel for data transmission

☞Transmit Big Data Over connections (unlimited data size)

☞The three-way handshake is a reliable protocol for Secure delivery.

Note: There are three handshakes before establishing a Communication Connection (pipe connection) to ensure data security and reliability (secure and reliable data transmission to the other party ).

Example: Call (understanding three handshakes)

The first handshake: Pick up the phone and dial. The dialing process is called the first handshake. [Start to prepare for connection]

The second handshake: the other party "Fed" and responded. I heard it, called the second handshake. [It indicates that I have no problem connecting you]

The third handshake: I heard the other party say "Hello" (responding). I also habitually "hello" and the other party heard it. [It indicates that you are connected to me]

If there are no problems in these three processes, you can confirm that the call connection is established successfully.

☞You must establish a connection to reduce the efficiency. (Each request requires a connection)

 

2. UDP (User Datagram Protocol)-> do not establish a connection (for example, send packets continuously when this is used for broadcast)

☞Encapsulate data, source, and target into data packets without establishing a connection

☞The maximum size of each datagram is 64 KB.

☞The Protocol is unreliable because no connection is required.

For example, when I read the instructor's broadcast lecture, I got a network card and saw the latest video content. I may miss some content.

☞No need to establish a connection, fast (saving three handshakes)

Iv. Socket Communication Flowchart

☞Bind (): bind port (80, 3306)

☞Listen (): listening port (whether the server listening client is connected to this port)

☞Accept (): if there is a connection to this port, it will receive this connection. (Communication Pipeline is connected, and data can be transmitted next)

☞Write (): Send requests/write requests/send data

☞Read (): read Request/read data

  • The underlying layer of HTTP is Socket communication. A connection (Communication Pipeline) is established through Socket to realize data transmission. The connection mode (data transmission mode) is TCP.
  • HTTP is a TCP transmission protocol. It is a reliable and secure protocol.

5. Experience Socket

Implement Socket server listening:

1) Use the C language.

2) The third-party framework (OC) of CocoaAsyncSocket is used to encapsulate C internally.

 

Telnet command: the service corresponding to a port on the connection server.

Telnet command: telnet host port

For example, telnet www.baidu.com 80 (the host can be found with the same IP address and domain name .)

 

1. [case] Write A 10086 service to experience Socket communication between the client and the server

☞Write a server by yourself and use a terminal instead of the client to demonstrate

☞MASTER: How to receive data and return data in the server through the Socket object.

  

/// ----- MyServiceListener. h ----- @ interface MyServiceListener: NSObject // enable service-(void) start; @ end // ----- MyServiceListener. m ----- # import "MyServiceListener. h "# import" GCDAsyncSocket. h "/*** service listener (server listening client connection) */@ interface MyServiceListener () <GCDAsyncSocketDelegate>/** Save the Socket object of the server */@ property (nonatomic, strong) GCDAsyncSocket * serviceSocket;/** save all Socket objects of the client */@ property (nonatomic, strong) NSMutableArray * clientSocketArr; @ end @ implementation MyServiceListener-(GCDAsyncSocket *) serviceSocket {if (! _ ServiceSocket) {// 1. create a Socket object // The Socket on the serviceSocket server only listens to the queue in which the client requests the connection // queue: the queue in which the proxy method is called (the queue of the sub-thread) _ serviceSocket = [[GCDAsyncSocket alloc] initWithDelegate: self delegateQueue: Queue (0, 0)];} return _ serviceSocket;}-(NSMutableArray *) clientSocketArr {if (! _ ClientSocketArr) {_ clientSocketArr = [NSMutableArray array];} return _ clientSocketArr;}-(void) start {// enable 10086 service: 5288 // 2. bind the port + enable the listener NSError * error = nil; // The method in the framework does two things: bind the port and enable the listener [self. serviceSocket acceptOnPort: 5288 error: & error]; if (! Error) {NSLog (@ "10086 service enabled successfully! ");} Else {// the cause of failure is that the port is occupied by other programs NSLog (@" 10086 service opening failed: % @ ", error );}} # pragma mark -- this method is called if a client Socket is connected to the server. -(Void) socket :( GCDAsyncSocket *) serviceSocket didAcceptNewSocket :( GCDAsyncSocket *) clientSocket {static NSInteger index = 1; NSLog (@ "client [% ld] is connected to the server! ", Index ++); // 1. save the client's Socket (the client's Socket is released and the connection will be closed) [self. clientSockets addObject: clientSocket]; // provides services (the following content is printed when the client connects to the server) NSMutableString * serviceStr = [[NSMutableString alloc] init]; [serviceStr appendString: @ "========= welcome to 10086 online service ===========\ n"]; [serviceStr appendString: @ "Enter the following number to select a service... \ n "]; [serviceStr appendString: @" [0] online recharge \ n "]; [serviceStr appendString: @" [1] online complaint \ n "]; [serviceStr appendSt Ring: @ "[2] discount info \ n"]; [serviceStr appendString: @ "[3] special services \ n"]; [serviceStr appendString: @ "[4] Quit \ n"]; [serviceStr appendString: @ "===================================================== \ n "]; // The service end sends data to the Client [clientSocket writeData: [serviceStr dataUsingEncoding: NSUTF8StringEncoding] withTimeout:-1 tag: 0]; // 2. whether the listening client has data upload (parameter 1: timeout,-1 indicates no timeout)/*** timeout: timeout,-1 indicates no timeout * tag: identification function, no need to write 0 */[clientSocket ReadDataWithTimeout:-1 tag: 0] ;}# pragma mark -- the server reads data from client requests (sent. When the server receives client data, this method will be called-(void) socket :( GCDAsyncSocket *) clientSocket didReadData :( NSData *) data withTag :( long) tag {// 1. obtain the data sent by the client NSString * str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSInteger index = [self. clientSocketArr indexOfObject: clientSocket]; NSLog (@ "received data sent by the Client [% ld]: % @", index + 1, str ); // convert the string to the number NSInteger num = [str integerValue]; NSString * responseStr = nil; // Switch (num) {case 0: responseStr = @ "the online recharge service is suspended... \ n "; break; case 1: responseStr = @" online complaint service suspended... \ n "; break; case 2: responseStr = @" no discount info \ n "; break; case 3: responseStr = @" no special service \ n "; break; case 4: responseStr = @ "Congratulations, your exit is successful! \ N "; break; default: break;} // 2. the server processes the request and returns data to the Client [clientSocket writeData: [responseStr dataUsingEncoding: NSUTF8StringEncoding] withTimeout:-1 tag: 0]; // After writing the data, determine if (num = 4) {// if the client is removed, the connection [self. clientSockets removeObject: clientSocket];} // because of the internal implementation of the framework, each time you read the data, you must call a method to listen to the data (ensure that you can receive the data uploaded by the client for the second time) [clientSocket readDataWithTimeout:-1 tag: 0];} @ end // ----- ViewController. m ----- # import "ViewController. h "# import" MyServiceListener. h "@ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // 1. create a Service Listening object MyServiceListener * listener = [[MyServiceListener alloc] init]; // 2. start listening to [listener start]; // 3. enable the master running cycle so that the service cannot be stopped (the server must be permanently enabled) [[[nsunloop mainRunLoop] run];} @ endExperience Socket communication-simple code for server side 2. [case extension] write a message forwarding service (group chat server)
  • Connect multiple clients to the server.
  • When a client sends a message to the server, the server forwards the message to other connected clients.
  • It is equivalent to the prototype of a group chat.

  

/// MyService. h # import <Foundation/Foundation. h> @ interface MyService: NSObject/** enable service */-(void) startService; @ end // MyService. m # import "MyService. h "# import" GCDAsyncSocket. h "@ interface MyService () <GCDAsyncSocketDelegate>/** Save the Socket object on the server */@ property (nonatomic, strong) GCDAsyncSocket * serviceSocket; /** save all Socket objects on the client */@ property (nonatomic, strong) NSMutableArray * clientSocketArr; @ end @ implem Entation MyService // enable 10086 service: 5288-(void) startService {NSError * error = nil; // bind port + enable listening [self. serviceSocket acceptOnPort: 5288 error: & error]; if (! Error) {NSLog (@ "service enabled successfully! ");} Else {NSLog (@" failed to enable the Service! ") ;}# Pragma mark -- proxy method. If a client Socket is connected to the server, this method is called. -(Void) socket :( GCDAsyncSocket *) serviceSocket didAcceptNewSocket :( GCDAsyncSocket *) clientSocket {// The client port number is allocated by the system, the server Port number is our own NSLog (@ "client [Host: % @, Port: % d] connected to the server! ", ClientSocket. connectedHost, clientSocket. connectedPort); // 1. save the client's Socket (the client's Socket is released and the connection will be closed) [self. clientSocketArr addObject: clientSocket]; // 2. whether the listening client has data upload (parameter 1: time-out time,-1 indicates no time-out; parameter 2: ID function, do not need to write 0 now) [clientSocket readDataWithTimeout:-1 tag: 0] ;}# pragma mark -- the server reads data from client requests (sent. When the server receives client data, this method will be called-(void) socket :( GCDAsyncSocket *) clientSocket didReadData :( NSData *) data withTag :( long) tag {// 1. obtain the data sent by the client NSString * messageStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "receives the client [Host :%@, Port: % d: The sent data: % @ ", clientSocket. connectedHost, clientSocket. connectedPort, messageStr); // traverses the client array for (GCDAsyncSocket * socket in self. clientSocketArr) {if (s Ocket! = ClientSocket) {// do not forward it to yourself // 2. the server forwards the received message to another client [socket writeData: data withTimeout:-1 tag: 0] ;}// after reading the data, you must call the method to listen to data once (ensure that you can receive the data uploaded by the client for the second time) [clientSocket readDataWithTimeout:-1 tag: 0];}-(GCDAsyncSocket *) serviceSocket {if (! _ ServiceSocket) {// 1. create a Socket object // The Socket on the serviceSocket server only listens to the queue in which the client requests the connection // queue: the queue in which the proxy method is called (the queue of the sub-thread) _ serviceSocket = [[GCDAsyncSocket alloc] initWithDelegate: self delegateQueue: Queue (0, 0)];} return _ serviceSocket;}-(NSMutableArray *) clientSocketArr {if (! _ ClientSocketArr) {_ clientSocketArr = [[NSMutableArray alloc] init];} return _ clientSocketArr;} @ end // main. m # import <Foundation/Foundation. h> # import "MyService. h "int main (int argc, const char * argv []) {@ autoreleasepool {// 1. create a service Listening object MyService * service = [[MyService alloc] init]; // 2. start listening to [service startService]; // 3. enable the master running cycle so that the service cannot be stopped (the server must be permanently enabled) [[[nsunloop mainRunLoop] run];} return 0 ;}Experience Socket communication-implementation code of the group chat server:

 

 

Related Article

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.