socket--Analog Chat

Source: Internet
Author: User
Tags sendmsg

1, how to communicate between processes in the network?

The local interprocess communication (IPC) is available in a number of ways, but can be summarized in the following 4 categories:

    • Message delivery (pipeline, FIFO, Message Queuing)
    • Synchronization (mutex, condition variable, read-write lock, file and write record lock, semaphore)
    • Shared memory (anonymous and named)
    • Remote Procedure calls (Solaris Gate and Sun RPC)

But these are not the subject of this article! What we're talking about is how the processes in the network communicate? The first problem is how to uniquely identify a process, or the communication is out of the question! A process can be uniquely identified locally through the process PID, but this is not feasible in the network. In fact, the TCP/IP protocol family has helped us solve this problem, the network layer "IP address " can uniquely identify the host in the network, and the Transport layer " protocol + port " can uniquely identify the host application (process). By using triples (IP address, Protocol, port), the process of the network can be identified, and the process communication in the network can use this flag to interact with other processes.

Applications that use the TCP/IP protocol typically use the application programming interface: The UNIX BSD socket (socket) and the Unix System v Tli (already obsolete) to enable communication between network processes. For now, almost all applications are sockets, and now it's the network era, where process communication is ubiquitous, and that's why I say "everything is a socket."

2. What is a socket?

Above we know that the process in the network through the socket to communicate, then what is the socket it? Sockets originate from Unix, and one of Unix/linux's basic philosophies is that "all files" can be manipulated using the "open open–> Read and write write/read–> close" mode. My understanding is that the socket is an implementation of the pattern, the socket is a special kind of file, some of the socket function is the operation of it (read/write Io, open, close), these functions we introduced later.

The origin of the word socket

The first use in the area of networking was discovered in the IETF RFC33, published on February 12, 1970, by Stephen Carr, Steve Crocker, and Vint Cerf. According to the records of the American Museum of Computer History, Croker wrote: "The elements of a namespace can be called socket interfaces." A socket interface forms one end of a connection, and a connection can be specified entirely by a pair of socket interfaces. "This is about 12 years earlier than the BSD socket interface definition," added the Computer History Museum. ”

3. Basic operation of socket

Since the socket is an implementation of the "open-write/read-close" pattern, the socket provides the function interfaces for these operations. The following is an example of TCP, which introduces several basic socket interface functions.

3.1. Socket () function
int socket(int domain, int type, int protocol);

The socket function corresponds to the open operation of the normal file. The open operation of a normal file returns a file descriptor, and the socket () is used to create a socket descriptor (socket descriptor), which uniquely identifies a socket. The socket descriptor is the same as the file descriptor, and subsequent operations are useful to it, using it as a parameter to perform some read and write operations.

Just as you can give fopen a different parameter value to open a different file. When creating a socket, you can also specify different parameters to create different socket descriptors, the three parameters of the socket function are:

    • Domain: The Protocol field, also known as the Protocol Family (family). Common protocol families are af_inet, Af_inet6, af_local (or Af_unix,unix domain sockets), Af_route, and so on. The protocol family determines the socket address type, must use the corresponding address in the communication, such as Af_inet decided to use the IPv4 address (32 bits) and the port number (16 bit) combination, Af_unix decided to use an absolute path name as the address.
    • Type: Specifies the socket type. Common socket types are, Sock_stream, Sock_dgram, Sock_raw, Sock_packet, Sock_seqpacket, and so on (what are the types of sockets?). )。
    • Protocol: Therefore, the name of the idea is to specify the agreement. Commonly used protocols are, IPPROTO_TCP, IPPTOTO_UDP, IPPROTO_SCTP, IPPROTO_TIPC, respectively, they correspond to TCP transport protocol, UDP Transmission protocol, STCP transmission protocol, TIPC Transfer Protocol (this agreement will be discussed separately!) )。

Note: Not the above type and protocol can be arbitrarily combined, such as sock_stream can not be combined with IPPROTO_UDP. When protocol is 0 o'clock, the default protocol corresponding to type types is automatically selected.

When we call the socket to create a socket, it returns the socket descriptor that exists in the Protocol family (address family,af_xxx) space, but does not have a specific address. If you want to assign an address to it, you must call the bind () function, or the system will automatically randomly allocate a port when you call Connect (), listen ().

The above has been introduced. Let's start with a little practice.

First, we drag the following controls into the storyboard:

Encapsulate the connection server as a method

//1 connecting to a server-(BOOL) Connect: (NSString *) IP port: (int) port{//Create socket//The first parameter domain protocol cluster refers to the type of IP IPv4 af_inet//the second parameter, type of socket, is a stream socket sock_stream,//The Third parameter protocol protocol IPPROTO_TCP    intClientsocket =sockets (Af_inet, Sock_stream, ipproto_tcp); Self.clientsocket=Clientsocket; structsockaddr_in addr; Addr.sin_family=af_inet; Addr.sin_addr.s_addr=inet_addr (IP.    utf8string); Addr.sin_port=htons (port); intresult = Connect (Clientsocket, (Const structSOCKADDR *) &addr,sizeof(addr)); if(Result = =0) {        returnYES; }Else{        returnNO; }}

Encapsulates the sending and receiving data into a single method

-(NSString *) SENDANDRECV: (NSString *) sendmsg {//3 sending data to the server//Success returns the number of characters actually passed, failure returns-1    Const Char*msg =sendmsg.utf8string; ssize_t Sendcount= Send (Self.clientsocket, MSG, strlen (msg),0); NSLog (@"number of bytes sent%zd", Sendcount); //4 data returned by the receiving server//returns the number of bytes actually receiveduint8_t buffer[1024x768]; ssize_t Recvcount= recv (self.clientsocket, buffer,sizeof(buffer),0); NSLog (@"number of bytes received%zd", Recvcount); //converts a byte array to a stringNSData *data =[NSData Datawithbytes:buffer Length:recvcount]; NSString*recvmsg =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; returnrecvmsg;}

Finally, when you click on these 3 buttons, we call the encapsulated method separately.

#import "ViewController.h"#import<sys/socket.h>#import<netinet/inch.h>#import<arpa/inet.h>@interfaceViewcontroller () @property (weak, nonatomic) Iboutlet Uitextfield*Ipview, @property (weak, nonatomic) Iboutlet Uitextfield*Portview, @property (weak, nonatomic) Iboutlet Uitextfield*Sendmsgview, @property (weak, nonatomic) Iboutlet UILabel*Recvmsgview, @property (nonatomic, assign)intClientsocket;@end@implementationViewcontroller//Click the Connect button-(Ibaction) Connectclick: (ID) Sender {//connecting to a server[self connect:self.ipView.text port:[self.portview.text intvalue];}//Click the Send button-(Ibaction) Sendclick: (ID) Sender {Self.recvMsgView.text=[self sendAndRecv:self.sendMsgView.text];}//Click the Close button-(Ibaction) Closeclick: (ID) Sender {//Close ConnectionClose (self.clientsocket); NSLog (@"Close Connection");}

Operation Result:

socket--Analog Chat

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.