This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

These two days many students want to hear about Socket content! So it took a little time to prepare it, and the open lesson sharing was enough!

Here through the written form of record down, convenient everyone corresponding study

What is a Socket?

To understand what a Socket is, first need to understand TCP/IP, UDP! 📚

Transmission Control Protocol (TCP) /Internet Protocol (IP) is an industry-standard Protocol set designed for wide area Networks (WANs). User Data Protocol (UDP) is a Protocol corresponding to TCP. It belongs to the TCP/IP protocol family.

TCP/IP protocol familyIncludes the transport layer, network layer, and link layer. Now you know the relationship between TCP/IP and UDP.

If you’re not familiar with the seven-layer protocol model, take a look at 👇🏻 :

How does TCP/IP, UDP and socket relate?

Socket is the intermediate software abstraction layer of communication between application layer and TCP/IP protocol family. It is a group of interfaces. In the design mode, Socket is actually a facade mode, it hides the complex TCP/IP protocol family behind the Socket interface, for the user, a simple set of interfaces is all, let the Socket to organize data to conform to the specified protocol.

How to use the Socket

In fact, there are a lot of network related knowledge need to popular science, but the space is limited, if you are a little strange to this piece of beautiful young girl, you can buy some network related books

  • TCP/IP Volume 1: Protocols
  • Illustrated HTTP
  • Unix Network Programming
  • HTTPS authoritative Guide

Socket as a set of interfaces, so how to use? The following picture is a foreword: 👇

Socket transmission features:

  • 1: Data transmission isByte level.Data transmission can be customizedThe data volumesmall(For mobile apps: low cost)
  • 2: Short data transmission time and high performance
  • 3: Suitable for real-time information exchange between the client and the server
  • 4: can be encrypted, data security is strong

Because of these advantages, it is often used as an important medium for instant communication

The figure above is the back and forth communication between the client and the terminal through socket

Socket implementation using code:

1: createsocket

int socketID = socket(AF_INET, SOCK_STREAM, 0);
self.clinenId= socketID;
if (socketID == - 1) {
    NSLog(@"Failed to create socket");
    return;
}
Copy the code
  • domain: protocol domain, andAgreement family. Common protocol families areAF_INET,AF_INET6,AF_LOCAL(or theAF_UNIX.UnixThe domainSocket),AF_ROUTEAnd so on. The protocol family is decidedsocketIn communication, the corresponding address must be used, such asAF_INETDecided to useipv4A combination of address (32-bit) and port number (16-bit),AF_UNIXDecided to use an absolute pathname for the address.
  • type: Specifies the Socket type. Common socket types are as followsSOCK_STREAM,SOCK_DGRAM,SOCK_RAW,SOCK_PACKET,SOCK_SEQPACKETAnd so on. streamingSocket(SOCK_STREAM) is connection-orientedSocketFor connection-orientedTCPService applications. The datagram typeThe Socket (SOCK_DGRAM)It’s kind of connectionlessSocket, corresponding to the connectionless UDP service application.
  • protocol: Specifies a protocol. Common protocols includeIPPROTO_TCP,IPPROTO_UDP,IPPROTO_STCP,IPPROTO_TIPCAnd so on, respectivelyTCPTransport protocol,UDP transport protocol,STCPTransport protocol,TIPCTransport protocol.

Note: 1. Type and protocol can not be combined at will. For example, SOCK_STREAM can not be combined with IPPROTO_UDP. When the third parameter is 0, the system automatically selects the default protocol corresponding to the second parameter type.

  • The return value: returns the descriptor of the newly created socket on success or failureINVALID_SOCKET(LinuxFailure return- 1)

2: Establishes the connection

int result = connect(socketID, (const struct sockaddr *)&socketAddr, sizeof(socketAddr));

if(result ! =0) {
    NSLog(@"Link failed");
    return;
}
NSLog(@"Link successful");
Copy the code
  • Parameters of a: Socket descriptor
  • Parameters of the two: points to a data structuresockaddrPointer to, including the destination port and IP address
  • Three parametersSecond: parametersockaddrThe length can be passedSizeof (struct sockaddr)To obtain
  • The return value: Returns if the command succeeds0, return on failurenon-zeroError code,GetLastError().
struct sockaddr_in socketAddr;
socketAddr.sin_family = AF_INET;
socketAddr.sin_port   = SocketPort;
struct in_addr socketIn_addr;
socketIn_addr.s_addr  = SocketIP;
socketAddr.sin_addr   = socketIn_addr;
Copy the code
  • __uint8_t sin_len; If there is no member, the byte it occupies is incorporated intosin_familyMembers of
  • sa_family_t sin_family; In generalAF_INET(Address family)PF_INET(Protocol family)
  • in_port_t sin_port; / / port
  • struct in_addr sin_addr; // ip
  • char sin_zero[8]; It doesn’t mean anything. It’s just to keep upSOCKADDRStructures are aligned in memory

3: sends messages

if (self.sendMsgContent_tf.text.length == 0) {
    return;
}
const char *msg = self.sendMsgContent_tf.text.UTF8String;
ssize_t sendLen = send(self.clinenId, msg, strlen(msg), 0);
NSLog(@"Send %ld bytes",sendLen);
[self showMsg:self.sendMsgContent_tf.text msgType:0];
self.sendMsgContent_tf.text = @"";
Copy the code
  • s: A descriptor that identifies the connected socket.
  • buf: Buffer containing data to be sent.
  • len: Indicates the length of data in the buffer.
  • flags: Invoke execution mode.
  • The return value: Returns the number of bytes sent on success, or on failureSOCKET_ERROR.a Chinese counterpart3 bytes!UTF8Coding!

4: Receive the message

while (1) {
    uint8_t buffer[1024];
    ssize_t recvLen = recv(self.clinenId, buffer, sizeof(buffer), 0);
    if (recvLen == 0) {
        NSLog(@"Received zero bytes.");
        continue;
    }
    // buffer -> data -> string
    NSData *data = [NSData dataWithBytes:buffer length:recvLen];
    NSString *str= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"% @ % @" -- -,[NSThread currentThread],str);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showMsg:str msgType:1];
        self.sendMsgContent_tf.text = @"";
    });
}
Copy the code
  • Parameters of a: the clientsocket
  • Parameters of the two: Address of the received content buffer
  • Three parameters: Indicates the length of the received content cache
  • Four parameters: Receiving mode,0: Blocking, you must wait for the server to return data
  • The return value: Returns the number of bytes read on success, or on failureSOCKET_ERROR

The Socket to summarize

Socket use is still very simple! The reason iOS development is a little hard is because:

  • They’re all C functions
  • The function has many arguments and is unfamiliar
  • The Internet is the blind spot of knowledge

For more fool-proof development, check out the next chapter: CocoaAsyncSocket on TCP and UDP in action

CocoaAsyncSocket implements instant messaging

Master Heavy Content (18)-CocoaAsyncSocket to implement sketchpad functionality

PS to do some welfare for everyone:

  • [The first sentence of the article] This article has participated in the “Digitalstar Project”, won the creative gift package, challenge creative incentive money.

  • [Number of submissions] If ≥ 4 papers are submitted and each paper ≧ 800 words, successful participation will be eligible for the award selection

  • 【 Article Content 】 Non-title party; Integration of non-interview questions; Technical articles are preferred

  • 【 article Classification 】 Front-end, back-end, iOS, Android, other categories are invalid

  • [Comment Lottery] All articles that only participate in digitalstar can be entered into the comment lottery. Article writers can guide users to engage in quality interaction in the comments section.

    • Guidance: For example, at the end of the submission, write “Welcome to discuss in the comments section. The excavation authorities will draw 100 nuggets in the comments section after the excavation project. See the activity article for details of the lucky draw.”
    • Raffle gift: 100 pieces, including badges, slippers, mugs, canvas bags, etc., will be distributed at random
    • Drawing time: Within 3 working days after the end of project Diggnation, all articles that meet the rules will be officially posted in the comments section
    • Lucky draw: Nuggets official random draw + manual verification
    • Comment content: comments, suggestions and discussions related to the content of the article. General comments such as “treading on” and “learning” will not win the prize

The selection conditions

  • The following awards: article quality, article number of words, number of contributions, number of articles read, interactive data (likes, comments, favorites), interactive quality (whether the comments are related to the discussion/suggestion of the article content, etc.)
  • During the award evaluation, the operation students will check each article to see if there is any violation such as brushing amount. If there is any violation, all the activities that have participated in will be disqualified

“Welcome to the discussion in the comments section. The nuggets will be giving away 100 nuggets in the comments section after the diggnation project. See the event article for details.”

I read it and if you like the nuggets’ perimeter, give it a thumbs up and a comment about you and socket