Recently I am working on socket programming. I have summarized two experiences and hope to share them with you. Because it is a cainiao, I hope you can give me more advice on anything wrong.
The first experience is to call a function that introduces the ws2_32.dll library before creating a new socket. Otherwise, the server cannot connect to the client.
Because I used socket for the first time, I checked a lot of information, but I found a problem. I don't know why I called the function according to the data steps, but I couldn't connect it. After I checked msdn in detail, it was found that most of the data started from the socket call. In fact, there was another initialization function to be called before that.
If you use Platform SDK: Windows Sockets, you must call the wsastartup function before calling the socket function to create a new sockets. The wsastartup function is used to introduce the ws2_32.dll library. According to msdn, The wsastartup function must be the first Windows Sockets function called by an application or DLL, it allows applications or DLL to specify the required Windows Sockets version and retrieve the execution details of the specified Windows Sockets. The following Windows Sockets function can be used only after the wsastartup function is successfully called.
Similarly, if you are using the csocket class packaged by MFC, you need to call the afxsocketinit function before calling cresat to create a new socket. The afxsocketinit function is packaged with the wsastartup function, which has the same effect.
The second experience is that when using socket programming, every time a function such as bind and listen is called, if an error occurs, you can use the wsagetlasterror () function to get the wrong number. If it is a csocket class of MFC, use the getlasterror () function to get the wrong number. However, the resulting number is an integer, Which is meaningless for debugging. Therefore, we recommend that you use the following program to get the Chinese error message.
Lpvoid lpmsgbuf; formatmessage (latency | latency, 0, getlasterror (), makelangid (lang_neutral, sublang_default), // default language (lptstr) & lpmsgbuf, 0, null ); // display MessageBox (0, (lpctstr) lpmsgbuf, _ T ("getlasterror"), mb_ OK | mb_iconinformation); // release the memory: localfree (lpmsgbuf );
This is my 2-Point experience and I hope it will be helpful for beginners of socket.