Socket for iOS learning, iossocket

Source: Internet
Author: User

Socket for iOS learning, iossocket

Socket definition in Baidu encyclopedia

Two programs on the network exchange data through a two-way communication connection. one end of the connection is called a socket.

Description

The original meaning of Socket is "hole" or "Socket ". As the process Communication Mechanism of bsd unix, take the latter meaning. It is also called "socket". It is used to describe the IP address and port. It is a communication chain handle and can be used to implement communication between different virtual machines or different computers.

Hosts on the Internet run multiple service software and provide several services at the same time. Each service opens a Socket and binds it to a port. Different ports correspond to different services.

Socket is like a porous Socket, just as it was originally intended. A host is like a room with various sockets. Each socket has a serial number. Some sockets provide 220 v ac, some provide 110 v ac, and some provide cable TV programs. The customer software inserts the plug into a socket with different numbers to obtain different services.

As described above, the Socket must include the dual-transmission of communication, that is, the Client and server ).

  • The server uses the Socket listening port

  • The client initiates a connection

  • The server returns information, establishes a connection, and starts communication.

  • The client and server are disconnected.

Socket third-party GCDAsyncSocket: https://github.com/AlonerOwl/socket

I. server side:

When building on the server, we need to import third-party frameworks and some other C language packages.

#import "GCDAsyncSocket.h"#include <arpa/inet.h>#include <net/if.h>#include <ifaddrs.h>

1. Declare a socket and initialize the socket

/// The socket on the server end determines that local variables cannot be used and @ property (nonatomic, strong) GCDAsyncSocket * socket cannot be destroyed; // initialize socketself. socket = [[GCDAsyncSocket alloc] initWithDelegate: self delegateQueue: dispatch_get_main_queue ()];

2. Bind the port to listen for connection messages

Port Number setting: If the port number is greater than 1024, you cannot use the disconnected eg.8080 and 8800 that are already in use on the market. Therefore, you must make a security judgment when binding.

NSError * error; // bind the port and listen to the connection message BOOL result = [self. socket acceptOnPort: [self. portTextField intValue] error: & error];

3. Listen to the client, obtain the new socket connection, call the following method, and perform some logical processing

// Parameter 1: socket of the current server // parameter 2: New socket-(void) socket of the received client :( GCDAsyncSocket *) sock didAcceptNewSocket :( GCDAsyncSocket *) newSocket;

4. read messages

The socket that calls the reading method reads the messages carried by the socket (corresponding to the messages sent by the client)

//-1 does not limit the read time. The tag is a tag value [newSocket readDataWithTimeout:-1 tag: 0];

5. Write Data

It can be called by anyone who writes it.

// The string variable is the message we want to write. It needs to be converted to Data //-1, which means the same meaning as when reading the message, indicating that the time is not limited. // tag is the tag value, generally set it to 0 [newSocket writeData: [string dataUsingEncoding: NSUTF8StringEncoding] withTimeout:-1 tag: 0];

6. Read the socket message and run it after readDataWithTimeout.

It is mainly used to connect to the processing of received messages and forward the messages to another receiving client, so as to communicate with the two clients. The specific data format and logic are processed by themselves according to individual needs. The following method is used together with the readDataWithTimeout method. If the readDataWithTimeout method is available, the following method is used.

// Parameter 1: socket of the server // parameter 2: Data read by the server // parameter 3: Mark-(void) socket :( GCDAsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag;

7. Disable the server

Disconnect the socket from the server and then set it to nil.

# Pragma mark-Disable service-(IBAction) stopService :( NSButton *) sender {if (self. socket) {# disable [self. socket disconnect]; self. socket = nil; [self addInfoString: @ "Close service"];} else {[self addInfoString: @ "disabled, no need to repeat"];}

8. Listener connection disconnection

When the server is disconnected, it is called to process the socket storage list.

// Call when the connection has been disconnected, listen for disconnection, and process the socket storage list-(void) socketDidDisconnect :( GCDAsyncSocket *) sock withError :( NSError *) err {// [self addInfoString: [NSString stringWithFormat: @ "disconnected % @", err]; [self addInfoString: [NSString stringWithFormat: @ "disconnected"]; if ([self. clients allKeysForObject: sock]. count> 0) {// when the client is disconnected, perform some operations to delete the socket [self. clients removeObjectForKey: [self. clients allKeysForObject: sock] [0]; NSLog (@ "% @", self. clients);} else {// when the server socket is disconnected, process the client socket list [self. clients removeAllObjects]; NSLog (@ "% @", self. clients );}}

Ii. Client

When building the client, you need to import a third-party class

#import "GCDAsyncSocket.h"

1. Declare and initialize the client socket (similar to the server)

@ Interface ViewController () <response >{// client-side socket GCDAsyncSocket * _ clientSocket;} @ end_clientSocket = [[GCDAsyncSocket alloc] initWithDelegate: self delegateQueue: Response ()];

2. Connect to the server

// Parameter 1: Server IP address // parameter 2: server port number (port number bound to the server) // parameter 3: error message-(BOOL) connectToHost :( NSString *) host onPort :( uint16_t) port error :( NSError **) errPtr

3. Proxy method executed after connecting to the server

It is mainly used to read data from the server.

// Connect to the server-(void) socket :( GCDAsyncSocket *) sock didConnectToHost :( NSString *) host port :( uint16_t) port {NSLog (@ "connect to server"); _ serverSocket = sock; // read data [_ serverSocket readDataWithTimeout:-1 tag: 0];}

4. Read server feedback data

The method is the same as step 1 of the server. It processes and utilizes the server feedback data.

5. The methods for reading and writing messages are the same on the server end. I will not repeat them here. You can refer to the methods for reading and writing messages on the server.

3. The following is a simple version of Demo learned by myself. If you are interested, you can download it.

: Https://github.com/AlonerOwl/Socket-

 

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.