- Socket network Programming under Windows
- CLINET.C Client
- SERVER.C Server-side
- Implementation of UDP communication
- The code is as follows
has not been programmed in windows for a long time, this time because of the need to do a cross-platform network program, first wrote a simple example of network winSocket communication, so that later when the use of a reference.
winsockthe difference between programming and using Windows linux/unix is that there is a need for a first operation in Windows 初始化 , and an operation at the end 清理 . There are also libraries that need to be connected when compiling under Windows ws32_lib .
The general process is as follows
1. Initialization
/*加载Winsock DLL*/
WSADATA wsd;
if (WSAStartup(MAKEWORD(2 , 2) , &wsd) != 0) {
printf("Winsock 初始化失败!\n");
return 1;
}
2. Socket related function call
socket(...)
bind(...)
listen(...)
connect(...)
accept(...)
send/sendto
recv/recvfrom
3. Clean up
WSACleanup();
CLINET.C Client
The process of the client is simple.
- 1, first use
socket the function to produce an open socket file descriptor.
- 2, use the
connect function to connect the service side
- 3, using the same
read/recv read file function to receive data from the server, using write/send the function of writing files to send data to the server
The above is a typical TCP programming process, if it UDP does not need connect to go to the connection server directly using sendto functions to send data, using Recvfrom to receive data from the servers
SERVER.C Server-side
Server-side processes are slightly more complex than clients
- 1. Call to
socket open a socket handle
- 2. Call
bind to bind the socket handle to a port on one of the network ports
- 3, call
listen to set (enable) monitoring
- 4. Call
accept to wait for client connection
The above is a typical TCP programming process, if UDP so, then do not need 3,4 these two, directly use recvfrom to receive the data sent by the client.
Implementation of UDP communication
I do not write here TCP , because it is a local area network, it is simple to write a.
Here is the test in the virtual machine, the code see the last.
Http://www.cnblogs.com/oloroso/p/4613296.html
Socket network programming under Windows (Entry level)