Simple use of Socket, simple use of Socket
I. Socket:
- Socket, also known as "Socket"
- Two programs on the network exchange data through a two-way communication link. The end of the Connection becomes a socket
- Applications usually send requests or respond to network requests through "Sockets ".
Ii. Elements of network communication
- Requests on the network are established through socket and then communicate with each other.
- IP address (Unique Identifier of the host device on the Network)
- Port Number (locating Program)
Used to identify the logical address of a process and the identifier of different processes
Valid port: 0 ~ 65535, 0 ~ 1024 is used or reserved by the system. Port 1024 or above is recommended during development.
Communication rules --> common protocol: TCP UDP Iii. TCP and UDPTCP (Transmission Control Protocol)
- Establish links to form a channel for data transmission
- During summer vacation in the Link (data is not restricted)
- The link is completed through three handshakes. It is a reliable protocol and delivered securely.
- You must create a link, which is less efficient.
UDP (User Datagram Protocol)
- Encapsulate data and source and target data into data packets without establishing a link
- The size of each datagram is limited to 64 KB.
- The Protocol is unreliable because no link is required.
- No need to establish a link, fast
Iv. Socket Communication Flowchart
5. Implement Socket server listening
- Socket Implementation Method
1. using C language 2. Using a third-party framework of cocoaAsyncSocket (OC), C is encapsulated internally.
Telnet host port/telnet --> 192.168.10.10 5288 1. the telnet command is the service corresponding to a port on the server. 2. host: System Preference --> network --> IP 3. host: valid port: 0 ~ 65535, 0 ~ 1024 is used or reserved by the system. Port 1024 or above is recommended during development. 6. Simple implementation of code
- Add third-party framework cocoaAsyncSocket ---> https://github.com/robbiehanson/CocoaAsyncSocket
- Create a project: Pull GCDAsyncSocket. h GCDAsyncSocket. m from a third-party framework
- Create a service listener object
# Import "ServiceListen. h "// introduce the header file # import" GCDAsyncSocket. h "@ interface ServiceListen () <GCDAsyncSocketDelegate> // server object @ property (nonatomic, strong) GCDAsyncSocket * serverSocket; // save client object @ property (nonatomic, strong) NSMutableArray * NewSockets; // client socket object @ end @ implementation ServiceListen/*** lazy loading */-(NSMutableArray *) NewSockets {if (_ NewSockets = nil) {_ NewSockets = [NSMutableArray new];} return _ NewSockets ;}/*** Enable service method implementation */-(void) start {// enable the 10086 service // The socket on the server only listens to GCDAsyncSocket * serverSocket = [[GCDAsyncSocket alloc] initWithDelegate: self delegateQueue: dispatch_get_global_queue (0, 0)]; // bind the port and enable the listener, which means that NSError * error = nil has been enabled for the 10086 service; [serverSocket acceptOnPort: 5288 error: & error]; if (! Error) {NSLog (@ "10086 service enabled successfully");} else {NSLog (@ "failed to enable % @", error);} self. serverSocket = serverSocket;} # pragma mark has client socket link to server/*** has client socket link to server call ** @ param sock Server * @ param newSocket client */-(void) socket :( GCDAsyncSocket *) sock didAcceptNewSocket :( GCDAsyncSocket *) newSocket {NSLog (@ "server serverSocket % @", sock); NSLog (@ "client newSocket % @", newSocket ); // Save the socket [self. newSockets addObject: newS Ocket]; // The NSMutableString * serverStr = [NSMutableString string]; [serverStr appendString: @ "Welcome !!! Enter the following number to select a service! \ N "]; [serverStr appendString: @" [0] online recharge \ n "]; [serverStr appendString: @" [1] online complaint \ n "]; [serverStr appendString: @ "[2] discount info \ n"]; [serverStr appendString: @ "[3] Special Service \ n"]; [serverStr appendString: @ "[4] Quit \ n"]; [newSocket writeData: [serverStr dataUsingEncoding: NSUTF8StringEncoding] withTimeout:-1 tag: 0]; // check whether the client has data to upload. // Timeout:-1 indicates no Timeout. // tag: ID function. Now, [newSocket readDataWithTimeout:-1 tag: 0] is not used.} # pragma mark reads client request data/*** reads client request data ** @ param sock client * @ param data * @ param tag mark */-(void) socket :( GCDAsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag {// 1: NSData to NSString * str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "read data sock: % @", sock, str); // obtain the data returned by the client NSInteger code = [str integerValue]; // NSString * reponseStr = nil; switch (code) {case 0: reponseStr = @ "no recharge service .... \ n "; break; case 1: reponseStr = @" No employee currently .... \ n "; break; case 2: reponseStr = @" off discount .... \ n "; break; case 3: reponseStr = @" special service .... \ n "; break; case 4: reponseStr = @" Exit successful .... \ n "; break; default: break;} // 2. process the request and return the data to the Client [sock writeData: [reponseStr dataUsingEncoding: NSUTF8StringEncoding] withTimeout:-1 tag: 0]; if (code = 4) {// remove the client [self. newSockets removeObject: sock] ;}# every time warning reads data, it must call the method of monitoring data once [sock readDataWithTimeout:-1 tag: 0];}View Code
- Instantiate a Service Listening object and start listening
# Import <Foundation/Foundation. h> # import "ServiceListen. h "int main (int argc, const char * argv []) {@ autoreleasepool {// insert code here... NSLog (@ "Hello, World! "); // Create a service listening object ServiceListen * listen = [[ServiceListen alloc] init]; // start listening to [listen start]; // enable the main running loop, prevent the service from stopping [[nsunloop mainRunLoop] run];} return 0 ;}View Code
- Run the program and open the terminal --> link to the server