Use the socket write code mainly to see what your needs is. If you communicate, the content is important to make TCP mode. If the number of users is too much, it may be used to use the UDP mode. In TCP mode, the easiest way is to make the blocked mode: server: 1. Initialize the Socket environment, create a socket2. 定 One port 3. Start listening 4. Receive the client 5. After receiving the client, Use this socket to communicate with this customer
#include "stdafx.h" #include
Using namespace std;
#pragma comment (lib, "ws2_32.lib") # Pragma Comment (Lib, "Mswsock.lib")
DWORD INISOCKDLL () {Word WVersionRequested; Int Err = 0; WVersionRequested = MakeWord (2, 2); Err = WSAStartup (WversionRequested, & Wsadata); Return Err;}
INT Main (int Argc, char * argv []) {cout << "program start" << Endl; Inisockdll (); socket ss = wsasocket (AF_INET, SOCK_STREAM, 0, NULL, 0, NULL); SOCKADDR_IN Addr; Int Len; addr.sin_family = afd_inet; addr.sin_addr.s_addr = htonl (inaddr_any); addr.sin_port = htons (1002); len = sizeof (addr); bind (s, (psockaddr) & addr, len; listen , 5); Socket SC = Accept (SS, (PSockAddr) & Addr, & Len; Char Buff [1024]; ZeromeMory (BUFF, 1024); RECV (SC, BUFF, 1024, 0); COUT << Buff << ENDL ZeromeMory (BUFF, 1024); MEMCPY (BUFF, "123", 3); Send (SC, BUFF, 3, 0); ClosSocket (SC); CloseSocket (SS); Return 0;}
Client: 1. Initialize the socket environment, create a socket2. Connect the server 3. Turn on a thread to receive data 4. Use the SEND direct data package
#include "stdafx.h" #include
Using namespace std;
#pragma comment (lib, "ws2_32.lib") # Pragma Comment (Lib, "Mswsock.lib")
DWORD INISOCKDLL () {Word WVersionRequested; Int Err = 0; WVersionRequested = MakeWord (2, 2); Err = WSAStartup (WversionRequested, & Wsadata); Return Err;}
INT Main (int Argc, char * argv []) {inisockdll (); socket sc = wsasocket (AF_INET, SOCK_STREAM, 0, NULL, 0, NULL); SockAddr_in addr; int Len; addr.sin_family = af_inet; addr.sin_addr .s_addr = inet_addr ("127.0.0.1"); addr.sin_port = htons (1002); len = sizeof (addr); Connect (sc, (struct sockaddr *) & addr, len); Char Buff [1024]; ZeromeMory BUFF, 1024); MEMCPY (BUFF, "123", 3); Send (SC, BUFF, 3, 0); RECV (SC, BUFF, 1024, 0); COUT << BUFF << end1
CloseSocket (SC); Return 0;}
From this we can make a model: open a thread for each blocking function, let it process. This should pay attention to the thread to close the thread when you pay.