Nagging
In the development of client-side game, the use of HTTP for network communication is relatively small, it is generally used to communicate with the socket. And HTTP is usually used for Web pages or web games.
Use a third-party socket Communication library:Odsocket.
Reference
http://blog.csdn.net/sight_/article/details/8138802 (Socket detailed)
http://blog.csdn.net/hguisu/article/details/7444092 (Socket Programming principle)
"Source Download"
Odsocket Library Source : Https://github.com/shahdza/Cocos_LearningTest/tree/master/ODSocket
This section of the demo source : Https://github.com/shahdza/Cocos_LearningTest/tree/master/ODSocket_Demo1
"Introduction to Sockets"
1. Socket (socket) concept
Socket (socket) is the cornerstone of communication and is the basic operating unit of network communication supporting TCP/IP protocol. It is an abstract representation of the endpoint in the network communication process and contains five kinds of information that must be used for network communication: the protocol that the connection uses, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol port of the remote process.
Socket: {IP address: port number}
When the application layer communicates data through the transport layer, TCP encounters a problem that provides concurrent services for multiple application processes at the same time. Multiple TCP connections or multiple application processes may require data to be transmitted over the same TCP protocol port. To differentiate between different application processes and connections, many computer operating systems provide a socket (socket) interface for applications interacting with the TCP/IP protocol. The application layer can communicate with the transport layer through the socket interface, differentiate the communication from different application processes or network connections, and realize the concurrent service of data transmission.
2. Socket type
The socket for TCP/IP provides the following three types of sockets.
2.1. Flow socket (SOCK_STREAM)
Provides a connection-oriented (TCP), reliable data transfer service that is error-free, non-repeatable, and received in the order sent. Internal flow control to avoid data flow overrun, data is considered as a byte stream, no length limit. File Transfer Protocol (FTP) uses streaming sockets.
2.2. Datagram-type sockets (SOCK_DGRAM)
Provides a non-connected service (UDP). Packets are sent in a separate package, without error-free guarantees, data may be lost or duplicated, and the order of reception is confusing. The Network File system (NFS) uses a datagram socket.
2.3. Original socket (SOCK_RAW)
This interface allows direct access to lower-level protocols such as IP and ICMP. Often used to verify a new protocol implementation or to access new devices that are configured in an existing service.
3. Establish socket connection
Establishing a socket connection requires at least one pair of sockets, one running on the client, called Clientsocket, and the other running on the server side, called ServerSocket.
The connection between sockets is divided into three steps: Server listening, client request, connection acknowledgement.
(a) server monitoring: The server-side socket does not locate a specific client socket, but is in a state of waiting for the connection, monitoring the network status in real time, waiting for the client's connection request.
(b) client request: refers to the client's socket to make a connection request, and the target to connect to is the server-side socket. To do this, the client's socket must first describe the socket of the server it is connecting to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.
(c) connection confirmation: When a server-side socket hears or receives a connection request to a client socket, it responds to a client socket request, establishes a new thread, sends a description of the server-side socket to the client, and once the client confirms the description, the two parties formally establish the connection. While the server-side socket continues to be in the listening state, it continues to receive connection requests from other client sockets.
4. Typical socket Invocation procedure example
The application of TCP/IP protocol generally uses the client/server mode , so in practical application, there must be two processes of client and server, and start the server first, the system call sequence diagram is as follows.
the socket system for connection-oriented protocol (TCP) is called as follows:
The > server must be started first until it executes the accept () call and enters the wait state before it can receive client requests.
> If the customer starts before this, connect () returns an error code and the connection is unsuccessful.
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5A/2A/wKioL1T4VXzzq03rAADiotwOa-I426.jpg "title=" Socket.jpg "alt=" Wkiol1t4vxzzq03raadiotwoa-i426.jpg "/>
the socket for the non-connected protocol (UDP) is called as follows:
> A non-connected server must also be started, otherwise the client request cannot pass the service process.
> No connect customer does not call connect (). Therefore, before the data is sent, the client and the server have not yet established a complete correlation, but each has established a semi-correlation through the socket () and bind ().
> When sending data, the sender must specify the receiver socket size in addition to the local socket size, thus dynamically establishing the full correlation in the data receiving and sending process.
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/5A/2A/wKioL1T4XJujlOgTAAEmgJegDDQ728.jpg "title=" 5.jpg " alt= "Wkiol1t4xjujlogtaaemgjegddq728.jpg"/>
"Socket Connection"
A connection-oriented TCP socket system call API is used.
0, the Odsocket source is stacked in the classes directory
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/5A/2E/wKiom1T4YG3Q7SI3AACCGDQxWCs165.jpg "title=" 7.png " alt= "Wkiom1t4yg3q7si3aaccgdqxwcs165.jpg"/>
1, the Client
Use the Odsocket API to implement network connectivity to the server.
> Create Odsocket:odsocket socket;
> Initialization:init(), Create();
> Set the IP address and port number of the server you want to connect to:IP , port;
> Connection server:connet(IP, port);
> Send data:Send (string, lenght);
> Received data:Recv(string, lenght, 0);
> Close connection:close();
The code is as follows:
Introduction Header file #include "odsocket/odsocket.h"// socker Connection Void helloworld::connectserver () { // initialization // ODSocket socket; Socket. Init (); socket. Create (af_inet, sock_stream, 0); // sets the IP address of the server, Port number // connect to server connect const char* ip = "127.0.0.1"; int port = 12345; bool Result = socket. Connect (ip, port); // send data Send socket. Send ("Login", 5); if (Result) { cclog ("connect to server success!"); // opens a new thread, in the child thread, receives the number ofAccording to std::thread recvthread = std::thread (& Helloworld::receivedata, this); recvthread.detach (); Detach from main thread } else { cclog ("Can not connect to server"); return; }}// receive Data void helloworld::receivedata () { // because it is strong networking // it can always detect if there is data coming from the server while (True ) { // receive Data Recv char data[512] = ""; int Result = socket. RECV (data, 512, 0); printf ("%d", result); // connection to the server has been disconnected if (result <= 0) break; cclog ("%s", data); } // Close Connection socket. Close ();} //
2. Service side
using the Eclipse development environment, the Java language, the server uses ServerSocket to listen for ports.
2.1. Server Class
Used to create ServerSocket, listen for port, wait for customer to connect.
public class Server {public static void main (string[] args) throws IOException {//create ServerSocket, listening port number: 12345ServerSock ET ss = new ServerSocket (12345);//Create a sub-thread class to manage the sending and receiving data for the client clientthread clientthread = new Clientthread (); Clientthread.start (); SYSTEM.OUT.PRINTLN ("Server on");//Listener port number: 12345//Waiting for Client connection accept () while (true) {//Start receiving client connection socket socket = ss.accept (); SYSTEM.OUT.PRINTLN ("New Client Connection ~"); clientthread.addclient (socket);}}} //
2.2, Clientthread class
For managing, processing, and receiving data requests from clients.
Inherit thread thread class public class clientthread extends thread {// Socket list for client connections private arraylist<socket> clients = new arraylist<socket> () ;// Add Customer public void addclient (socket socket) {clients.add (Socket);} Delete Customer public void removeclient (socket socket) {clients.remove (Socket);} Send data to customers Public void sendmessage (Socket socket, string data) throws ioexception {// send data to the player Outputstream os = socket.getoutputstream (); Os.write ( Data.getbytes ("UTF-8"));} @Overridepublic void run () {while (True) {try {for (socket socket : clients) {// get the data sent by the client inputstream is = socket.getinputstream (); int len = is.available () + 1;byte[] buff = new byte[len];int Flag = is.read (buff);// read () return-1, indicating guestThe socket of the client has been disconnected if (flag == -1) {system.out.println ("Customer disconnected ~"); this.removeclient (socket); break;} Output received data string read = new string (buff); System.out.println ("Received data:" + read);// to send data to the player string data = "Congratulations, the connection is successful ~ ~"; SendMessage (socket, data);} Sleep (10);} catch (ioexception e) {e.printstacktrace ();} catch (interruptedexception e) {e.printstacktrace ();}}} //
3. Running the server
In the Eclipse development tool, run the server program.
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/5A/2A/wKioL1T4ZPSzVwF1AACwrBtVgZk631.jpg "title=" 9.png " alt= "Wkiol1t4zpszvwf1aacwrbtvgzk631.jpg"/>
4. Running the client
Then run the client to try it.
Client output:
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/5A/2A/wKioL1T4ZV7wQOXOAAC90bbKLnk301.jpg "title=" 11.png "alt=" Wkiol1t4zv7wqoxoaac90bbklnk301.jpg "/>
Service-Side output:
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/5A/2F/wKiom1T4ZFahJIbHAACGKVdOmg0347.jpg "title=" 12.png "alt=" Wkiom1t4zfahjibhaacgkvdomg0347.jpg "/>
5. Close the client program
Service-Side output:
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/5A/2A/wKioL1T4ZafwYHPVAACkPM2wI_c458.jpg "title=" 13.png "alt=" Wkiol1t4zafwyhpvaackpm2wi_c458.jpg "/>
Cocos Network Chapter [3.2] (3)--socket connection (1)