Server Common Model
(1) Initialize the monitor socket
Initialize socket
= socket (af_inet,socket_stream,ipproto_tcp); // create a socket as a listening port // socket type is stream socket // the network protocol used is the TCP protocol // Socket Family value is af_inet
Bind socket
== inet_addr ("127.0.0.1"= Htnos (9000); bind (s), ( LPSOCKETADDR)&addr,sizeof(addr)); // Socket Family value is af_inet // server address is 127.0.0.1 // the server uses a port of 9000
Start listening.
Listen (s,somaxconn); // Maximum number of connections system set maximum value
(2) Establishing a connection
Detecting socket Status
The function Select detects the corresponding socket state to determine whether a new connection needs to be established.
00; Fd_zero (&Readset); Fd_set (S,&readset); int Select (fd_setsize,&readset,null,null,&timeout); if (ret>0&&fd_isset (s,&// New connection }
Create a new connection
Establish a new connection if the client has a new connection request fed
sockaddr_in addr; int sizeof = Accept (S, (sockaddr*) &addr, (socklen_t*) &len); if (temp = = Invalid_socket) {// connection failed }
(3) Send and receive data
Detecting read-in data
00; Fd_zero (&Readset); Fd_set (S,&reader); int Select (fd_setsize,&readset,null,null,&timeout); if (ret>0&&fd_isset (s,&readset)) {// with new data }
Receive data
Char buf[1024x768]; int = recv (s,buf,1024x768,0);
Detect sending Data
00; Fd_zero (&Wtiteset); Fd_set (S,&writeset); int Select (fd_setsize,&writeset,null,&timeout); if (ret>0&&fd_isset (s,&writeset)) {// can send data }
Send data
Char buf[1024x768]; int = Send (S,buf,1024x768,0);
(4) Close the connection
Closesocket (s);
Client Common model
(1) Initialize socket
Create socket
= socket (af_inet,socket_stream,ipproto_tcp); // create a socket as a listening port // socket type is stream socket // the network protocol used is the TCP protocol // Socket Family value is af_inet
The types of sockets that the client and server side choose are consistent.
Binding port
The client's IP address and port number do not need to be fixed and can be assigned automatically by the system.
== = htons (0); Bind (S, (LPSOCKADDR)&addr,sizeof(addr)); // Socket Family value is af_inet // the client IP address and port are specified by the system
(2) Establishing a connection
When sending a connection request, you need to specify the port number and IP address of the server.
serveraddr.sin_family=af_inet; Serveraddr.sin_port=htons (9000); ServerAddr.sin_addr.s_addr=inet_addr ("127.0.0.1"); Connect (s, (Sockadd* ) &serveraddr,sizeof(serveraddr)); // Server Socket Family value is af_inet // Server port number is 9000 // Server IP address is 127.0.0.1
(3) Send and receive data
Same as Server
(4) Close the connection
Same as Server
1th Network Programming Basics (3)-Basic socket communication