Cocos2d-x network module 3: Socket connection (1)

Generally speaking, in client game development, it is rare to use HTTP for network communication, and Socket is generally used for communication. HTTP is mainly used for web pages or web games.

Use third-party socket communication library: ODSocket.

Introduction to Socket

1. The concept of sockets

       Socket is the cornerstone of communication and the basic operation unit of network communication supporting TCP/IP protocol. It is the abstract representation of the endpoint in the network communication process, including five kinds of information necessary for network communication: the protocol used for the connection, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol of the remote process port.

Socket: {IP address: port number}

        When the application layer communicates data through the transport layer, TCP will encounter the problem of providing concurrent services for multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP protocol port. In order to distinguish between different application processes and connections, many computer operating systems provide a socket (Socket) interface for the application to interact with the TCP/IP protocol. The application layer and the transport layer can distinguish the communication from different application processes or network connections through the Socket interface, and realize the concurrent service of data transmission.

2. Socket type

TCP/IP socket provides the following three types of sockets.

2.1, streaming socket (SOCK_STREAM)

       Provides a connection-oriented (TCP), reliable data transmission service, data is sent error-free, repeat-free, and received in the sending order. Built-in flow control to avoid data flow exceeding the limit; data is regarded as a byte stream without length limitation. The File Transfer Protocol (FTP) uses streaming sockets.

2.2. Datagram socket (SOCK_DGRAM)

       A connectionless service (UDP) is provided. The data packets are sent in the form of independent packets, no error-free guarantee is provided, the data may be lost or duplicated, and the receiving order is disordered. The Network File System (NFS) uses datagram sockets.

2.3, raw socket (SOCK_RAW)

       This interface allows direct access to lower layer protocols such as IP and ICMP. It is often used to verify the implementation of a new protocol or access new equipment configured in an existing service.

3. Establish a socket connection

       Socket connection requires at least a pair of sockets, one of which runs on the client side, called ClientSocket, and the other runs on the server side, called ServerSocket.

The connection process between sockets is divided into three steps: server monitoring, client request, and connection confirmation.

(a) Server monitoring: The server-side socket does not locate a specific client socket, but is in a state of waiting for connection, monitoring the network status in real time, and waiting for the client's connection request.

(b) Client request: refers to the connection request made by the socket of the client, and the target of the connection is the socket of the server. For this reason, the socket of the client must first describe the socket of the server to which it is connected, point out 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 the server socket monitors or receives the connection request of the client socket, it responds to the request of the client socket, establishes a new thread, and connects the server socket The description of is sent to the client. Once the client confirms the description, the two parties will formally establish a connection. The server socket continues to be in the listening state and continues to receive connection requests from other client sockets.

4. Examples of typical socket calling process

       The application of the TCP/IP protocol generally adopts the client/server model, so in actual applications, there must be two processes, a client and a server, and the server is started first. The system call sequence diagram is as follows.

       The socket system calls of the connection-oriented protocol (TCP) are as follows:

> The server must be started first, until it finishes the accept() call and enters the waiting state before it can receive client requests.

> If the client started before, connect() will return an error code and the connection is unsuccessful.

 

 

The socket call of the connectionless protocol (UDP) is as follows:

> The connectionless server must also be started first, otherwise the client request will not be transmitted to the service process.

> No connection client does not call connect(). Therefore, before the data is sent, the client and the server have not yet established a complete correlation, but they have established a semi-correlation through socket() and bind().

> When sending data, in addition to specifying the local socket number, the sender also needs to specify the receiver socket number, so that the full correlation is dynamically established during the data transmission and reception process.

 

 

[Socket connection]

The connection-oriented TCP socket system call API is used.

0. Put the ODSocket source code in the Classes directory

 

 

1. Client

Use the ODSocket API to realize the network connection with the server.

> Create ODSocket: ODSocket socket;

> Initialization: Init(), Create();

> Set the IP address and port number of the server to be connected: ip, port;

> Connect to the server: Connet(ip, port);

> Send data: Send(string, lenght);

> Receive data: Recv(string, lenght, 0);

> Close the connection: Close();

code show as below:

//

// Import header file

#include "ODSocket/ODSocket.h"

// Socker connection

void HelloWorld::connectServer()

{

// Initialize

// ODSocket socket;

socket.Init();

socket.Create (AF_INET, SOCK_STREAM, 0);

// Set the IP address and port number of the server

// And connect to the 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!");

// Start a new thread, in the child thread, receive data

std::thread recvThread = std::thread(&HelloWorld::receiveData, this);

recvThread.detach(); // detach from the main thread

}

else {

CCLOG("can not connect to server");

return;

}

}

// Receive data

void HelloWorld::receiveData()

{

// because of strong networking

// So you can always check whether 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);

// disconnected from the server

if (result <= 0) break;

CCLOG("%s", data);

}

// close the connection

socket.Close();

}

//

2. Server

Using Eclipse development environment, Java language, the server uses ServerSocket to monitor the port.

2.1, Server class

Used to create ServerSocket, monitor port, and wait for client connection.

//

public class Server {

public static void main(String[] args) throws IOException {

// Create ServerSocket, monitor port number: 12345

ServerSocket ss = new ServerSocket(12345);

// Create a child thread class used to manage the client's sending and receiving data

ClientThread clientThread = new ClientThread();

clientThread.start();

System.out.println("Server is on");

// Listening port number: 12345

// Wait for the client to connect accept()

while (true) {

// Start receiving client connections

Socket socket = ss.accept();

System.out.println("There is a new client connection~");

clientThread.addClient(socket);

}

}

}

//

2.2, ClientThread class

It is used to manage and process the client's sending and receiving data requests.

//

// Inherit the Thread thread class

public class ClientThread extends Thread {

// List of sockets connected by the client

private ArrayList clients = new ArrayList();

// 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"));

}

@Override

public 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() returns -1, indicating that the client's socket has been disconnected

if (flag == -1) {

System.out.println("A client disconnected~");

this.removeClient(socket);

break;

}

// output the received data

String read = new String(buff);

System.out.println("Data received:" + read);

// 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. Run the server

In the Eclipse development tool, run the server program.

 

 

4. Run the client

Then try running the client.

Client output:

 

 

Server output:

 

 

5. Close the client program

Server output:

 

 

In the Eclipse development tool, run the server program.

Guess you like

Origin blog.csdn.net/qq_21743659/article/details/108660410