Socket in the definition of Baidu Encyclopedia
The two programs on the network realize the exchange of data through a two-way communication connection, one end of this connection is called a socket.
Related description
The English literal of the socket is "hole" or "socket". As the BSD UNIX process communication mechanism, take the latter one meaning. Often also referred to as a "socket," which describes IP addresses and ports, is a handle to a communication chain that can be used to communicate between different virtual machines or different computers.
Hosts on the internet typically run multiple service software, while providing several services. Each service opens a socket and binds to a port, and the different ports correspond to different services.
The socket is like a porous socket, as its English intended. A host is like a room full of various sockets, each outlet has a number, some sockets provide 220 vac, some provide 110 volts AC, some provide cable TV programs. Customer software plug into different numbered sockets, you can get different services.
As described above, the socket must contain a double-ended communication, that is, the client and the server.
-
The server uses the socket listener port
-
Client initiated Connection
-
The server returns information, establishes the connection, and begins the communication.
-
Client, service-side disconnect
Socket third-party gcdasyncsocket: Https://github.com/AlonerOwl/socket
First, server-side:
When building on the server side, we need to import third-party frameworks and some other C-language packages
#import " GCDAsyncSocket.h " <arpa/inet.h><net/if.h><ifaddrs.h>
1. Declare a socket and initialize the socket
/// server-side socket, decided not to use local variables, can not be destroyed @property (nonatomic, Strong) Gcdasyncsocket *socket; // Initialize socketself.socket = [[Gcdasyncsocket alloc] initwithdelegate:self delegatequeue:dispatch_get_main_queue ()];
2. Binding port, listening for connection messages
Port number setting: Port number greater than 1024, can not use the market has been occupied with the disconnect eg.8080,8800, so at the time of binding, to make a security judgment.
Nserror *error; // binding port, listening for connection messages BOOL result = [Self.socket Acceptonport:[self.porttextfield intvalue] error:&error];
3, listen to the client, get a new socket connection, call the following methods, and do some logical processing
// parameter 1: Socket for current server // Parameter 2: Incoming client's new socket-(void) Socket: (Gcdasyncsocket *) sock didacceptnewsocket: (Gcdasyncsocket *) Newsocket;
4. Read messages
The Read method is which socket call will read which socket carries the message (corresponding to the client sending the message)
// -1 does not limit read time, tag is a tag value [Newsocket readdatawithtimeout:-1 tag:0];
5. Write Data
Write to whoever you want to call
// The string variable is the message we want to write and it needs to be converted to data // -1 is the same as when reading a message, which means no time limit // Tag is a tagged value and is generally set to 0 [Newsocket writedata:[string datausingencoding:nsutf8stringencoding] withtimeout:-1 tag:0 ];
6, read the message to the socket, execute after readdatawithtimeout
It is mainly used for processing the received message and forwarding the message to another receiving client, so it can communicate with two clients, and the specific data format and logic will be handled according to the individual requirement. The following methods and readdatawithtimeout methods, as long as there is a readdatawithtimeout method, there will be the following method
// parameter 2: Data read by server // Parameter 3: Token -(void) Socket: ( Gcdasyncsocket *) sock didreaddata: (NSData *) data withtag: (long) tag;
7. Shut down the server
Set the server's socket to nil after disconnecting it
#pragma mark-Close service-(ibaction) StopService: (Nsbutton *) sender{ if (self.socket) { #warning close [self.socket disconnect]; = Nil; [Self addinfostring: @" Close Service " ]; Else { [self addinfostring:@ ' has been closed without repetition ']; }}
8, listen to the disconnection of the connection
Called when the server disconnects, primarily to handle the list of socket stores.
//called when a connection has been disconnected, listens for disconnection of the connection, and processes the socket storage list- (void) Socketdiddisconnect: (Gcdasyncsocket *) sock witherror: (Nserror *) err{//[self addinfostring:[nsstring stringwithformat:@ "disconnected%@", err]];[Self addinfostring:[nsstring stringWithFormat:@"already disconnected"]]; if([Self.clients allkeysforobject:sock].count >0) { //Some operations to remove the socket when the client disconnects[Self.clients removeobjectforkey:[self.clients allkeysforobject:sock][0]]; NSLog (@"%@", self.clients); } Else { //processing the client socket list when the server socket is disconnected[Self.clients removeallobjects]; NSLog (@"%@", self.clients); }}
Second, the client
When building the client side, you need to import third-party classes
#import " GCDAsyncSocket.h "
1. Declaring and initializing the client socket (similar to the server side)
@interface Viewcontroller () <GCDAsyncSocketDelegate>{ // client-side socket Gcdasyncsocket *_clientsocket;} @end = [[Gcdasyncsocket alloc] initwithdelegate:self delegatequeue:dispatch_get_main_queue ()];
2. Connect to the server
// parameter 2: port number of the server (server bound port number)// Parameter 3: Error message -(BOOL) Connecttohost: (nsstring*) host OnPort: (uint16_t) port error: (Nserror *) errptr
3. Proxy methods that are executed after connecting to the server
Primarily used to read data from the server
// Connect to Server -(void) Socket: (Gcdasyncsocket *) sock didconnecttohost: (NSString *) host port: (uint16_t) port{ NSLog (@ " connect to server "); = sock; // Read Data [_serversocket readdatawithtimeout:-1 tag:0];}
4, read the server feedback data
Method and the server 6th step method, the server feedback data processing and utilization
5, read and write the method of the message server side is the same, here I will not repeat the introduction, we can refer to the server read and write message method
Third, the following is a summary of their own study of the demo, interested friends can download to see
: https://github.com/alonerowl/socket-
The socket for iOS learning