[iOS5 cocos2d Game Development Combat] Note 4 socket

Source: Internet
Author: User
Tags new set htons

Socket

Connection

SOCKET sock_client;   = socket (af_inet, sock_stream, ipproto_tcp);   if (Invalid_socket = = sock_client)  {     "Invalid socket. " << Std::endl;     WSACleanup ();      return 0 ;  }  Sockaddr_in Addr_sev;   = af_inet;   = htons (port_server);   = Inet_addr ("127.0.0.1");   if sizeof (Addr_sev)))  {     "Failed to connect. " << Std::endl;     WSACleanup ();      return 0 ;  }  

Using POSIX to create threads see iOS note thread

Socket File Descriptor

Reference Link: http://blog.csdn.net/kjing/article/details/6962440

basic TCP Set interface programming this article is from: http://sunsland.top263.net Author: (2001-10-22 12:00:00)Overview socket ()--get the file descriptor! Bind ()--which port are we on? Connect ()--hello! Listen ()--did someone call me? Accept ()--"Thank for calling Port 3490."Send () and recv ()--talk to me, baby!sendto () and recvfrom ()--talk to me, dgram-style close () and shutdown ()--Get outta here! Getpeername ()--who are you? GetHostName ()--Who am I? DNSYou said "White House," I said."198.137.240.100"--------------------------------------------------------------------------------socket function: Specify protocol type definition: #include<sys/types.h>#include<sys/socket.h>intSocketintFamilyintTypeintprotocol); Error in return value:-1success: The set interface descriptor (socket file descriptor) (socket) SOCKFD socket function specifies the protocol family (IPV4, IPv6, or Unix) and the socket type (byte stream, datagram, or raw set interface).    However, there is no local protocol address or remote protocol address specified.    Understand how the socket socket communicates using Unix file descriptors (Files descriptor) and other programs. The Unix program performs any form of I/O, the program is reading or writing a file descriptor.    A file descriptor is just an integer associated with an open file. This file may be a network connection, FIFO, pipe, terminal, file on disk or something else. All the things in Unix are files! Therefore, when communicating with other programs on the Internet, pass the file descriptor. Use the system call socket () to get the file descriptor for network communication.    He returns a set of interface descriptors (socket descriptor) and then calls Send () and recv () through him.    So why not use a generic call to read () and write () to communicate through the socket interface?    The simple answer is: You can use the general function!      The detailed answer is: Use Send () and recv () to give you better control over the data transfer. --------------------------------------------------------------------------------Connect function: Establish a connection definition to a TCP server: #include<sys/types.h>#include<sys/socket.h>intConnectintSOCKFD,structSockaddr *serv_addr,intAddrlen); //SOCKFD is the set of interface file descriptors returned by the system call socket ()SERV_ADDR is a data structure that holds the destination port and IP addressstructsockaddr//Addrlen set to sizeof (struct sockaddr)connect excitation TCP's three-way handshake process The server must be ready to accept incoming connections.    This is done by calling the Socket,bind and 1isten functions, called passive open (Passive open) customers by calling Connect to open actively (active OPN).    This causes the client TCP to send a SYN subsection (for synchronization) that tells the server customer the initial sequence number of the data that will be sent in the (pending) connection. The server must confirm the SYN of the customer and also send a SYN section that contains the firmware sequence number of the data that the server will send in the same connection. The server sends a SYN to the customer and an ACK to the Customer SYN in a single subsection.    The customer must confirm the Syn of the server. Return error due to connect error: Response not received by SYN (server timeout, 75s) return value: Etimedout client output: Connection time out. Cause of error: Received RST response (hard error) SYN arrives at the server, but the server does not have this port service return value: Econnrefuse client output: Connection refused error cause: ICMP error: Non-routable (soft E rror) (Destination unreachable) return value: Ehostunreach user-side output: Enetunreach No route to host--------------------------------------------------------------------------------bind function Function: Assign a local protocol address definition to a socket: #include<sys/types.h>#include<sys/socket.h>intBindintSOCKFD,Const structSockaddr *my_addr,intAddrlen);    SOCKFD is the file descriptor returned by the calling socket. MY_ADDR is a pointer to the data structurestructA pointer to the SOCKADDR that holds the address (that is, port and IP address) information. Addrlen set tosizeof(structsockaddr). return:0-Success,-1---error allows kernel to automatically process address IP and ports port My_addr.sin_port=0;/*Choose an unused port at random*/my_addr.sin_addr.s_addr= Inaddr_any;/*Use my IP address*/bind () chooses the appropriate port for itself: assigns 0 to My_addr.sin_por.         Automatically fill in the IP address of the machine he is running: MY_ADDR.SIN_ADDR.S_ADDR is set to Inaddr_any. --------------------------------------------------------------------------------Listen function: Converts a non-connected active socket interface to a passive socket, indicating that the kernel accepts a connection request to the socket. CLOSED--?LISTEN definition: #include<sys/socket.h>intListenintSOCKFD,intbacklog);    SOCKFD is the set of interface file descriptors that are returned by the calling socket ().    The backlog is the number of connections allowed in the incoming queue. Two queues for the listening socket interface not complete connection queue (incompleted connection queue): Syn_recv completed connection queue (completed connection queue): established when a customer When a SYN arrives, such as two queues are full, TCP ignores the sub-section and does not send the RST--------------------------------------------------------------------------------the ACCEPT function function: Returns the next completed connection definition in the completed queue header #include<sys/socket.h>intAcceptintSOCKFD,structSockaddr *cliaddr,int*Addrlen); Returned when the call succeeds:1. CLIADDR: The protocol address and address size of the client process2. New set of interface descriptor (connected socket descriptor) Listener Interface Description Word listening socket descriptor a given server is often generated only by a single listener interface and persists until the server shuts down. Connected socket Description Word connected socket The descriptor core creates a connected socket interface for each accepted client connection.    When the server completes the service of a customer, the connected socket interface is closed. Ports below 1024: Super User use--------------------------------------------------------------------------------Fork function function: Derive new process CreateNewprocess definition: #include<sys/unistd.h>pid_t Fork (void); Returns 0 in a child process, returned when a process ID in the parent process returns a child process error1, call a typical application that returns two fork at a time:1. A process can create a copy for itself. When a copy processes an operation, other copies can perform other tasks.    This is a very typical Web server. 2.      One process wants to execute another program, because the only way to create a new process is to call fork, the process first calls fork to generate a copy, and then one copy (usually a child process) calls exec to execute the new program instead of itself. (http://www.fanqiang.com)--------------------------------------------------------------------------------------------------------------- --------------    ------------------------------------------------------------------------------------------------- ----------------------------Concurrent Server iterations Server iterative server single-process concurrent Server Concurrent Server multi-process when the connection is established, accept returns, the server calls the fork subprocess to serve the customer (through the CO    NNFD the socket interface is connected), the parent process waits for another connection (via the LISTENFD listener socket).    After the child process begins processing the new customer, the parent process closes the connected socket interface.    Each file or socket interface has an access count, which is maintained in a file table entry that represents the number of open descriptors currently pointing to the file or set of interfaces.    When returned from sock, the file table entry with the LISTENFD associated with the access count value is 1, and the file table entry that is associated with the CONNFD has an access count value of 1 when it is returned from accept.    When the fork returns, two descriptors are shared between the parent process and the child process (duplicated) and the two socket gates are associated with a file table entry that has an access count value of 2. When the parent process closes CONNFD, it simply cuts the access count value from 2 to 1.         The descriptor is closed only when the access-count value reaches 0 o'clock, which is encountered when the child process closes CONNFD at some later time. --------------------------------------------------------------------------------The close function functions: Make the socket "closed" and return to the process immediately.    Reduce the access counter of the socket descriptor by 1.    When the access counter value is 0 o'clock, a TCP four packet connection termination sequence is raised, which closes the socket interface. Definition: #include<sys/unistd.h>intCloseintSOCKFD); --------------------------------------------------------------------------------getsockname and Getpeername functions: getsockname: Returns the local protocol address getpeername: Returns the remote protocol address definition: #include<sys/unistd.h>intGetSockName (intSOCKFD,structSockaddr *localaddr,int*Addrlen); intGetpeername (intSOCKFD,structSockaddr *peeraddr,int*Addrlen); --------------------------------------------------------------------------------An example program: #include<string.h>#include<sys/types.h>#include<sys/socket.h>#defineMyPort 3490/* The port users would be connecting to * *#defineBACKLOG/* How many pending connections queue would hold * *Main () {intSOCKFD, NEW_FD;/*Listen on SOCK_FD, new connection on NEW_FD*/  structSockaddr_in my_addr;/*My address information*/  structSockaddr_in their_addr;/*connector ' s address information*/  intsin_size; SOCKFD= Socket (Af_inet, Sock_stream,0);/*Do some error checking!*/my_addr.sin_family= Af_inet;/*Host byte order*/My_addr.sin_port= Htons (MyPort);/*Short , network byte order*/my_addr.sin_addr.s_addr= Inaddr_any;/*Auto-fill with my IP*/bzero (& (My_addr.sin_zero),8);/*Zero The rest of the struct*/  /*don ' t forget your error checking for these calls:*/bind (SOCKFD, (structSOCKADDR *) &my_addr,sizeof(structsockaddr));  Listen (SOCKFD, BACKLOG); Sin_size=sizeof(structsockaddr_in); NEW_FD= Accept (SOCKFD, &AMP;THEIR_ADDR, &sin_size);  . . . . . . . . . . . . . 

Reference connection: http://blog.csdn.net/zzhboy/article/details/9878941 socket receive and send data

http://blog.csdn.net/zjl_1026_2001/article/details/2153222 Select function

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.