Create two projects respectively .. Copy CPP and run it...
Server:
# Include <winsock2.h>
# Include <stdio. h>
# Pragma comment (Lib, "ws2_32.lib ")
Void main ()
{
// Create a socket
Word myversionrequest;
Wsadata;
Myversionrequest = makeword (1, 1 );
Int err;
Err = wsastartup (myversionrequest, & wsadata );
If (! Err)
{
Printf ("opened socket \ n ");
}
Else
{
// Bind the socket further
Printf ("the nested word is not opened! ");
Return;
}
Socket sersocket = socket (af_inet, sock_stream, 0); // creates an identifiable socket
// Parameters to be bound
Sockaddr_in ADDR;
ADDR. sin_family = af_inet;
ADDR. sin_addr.s_un.s_addr = htonl (inaddr_any); // ip address
ADDR. sin_port = htons (6000); // bind the port
BIND (sersocket, (sockaddr *) & ADDR, sizeof (sockaddr); // The binding is complete.
Listen (sersocket, 5); // The second parameter indicates the maximum number of connections that can be received.
//////////////////////////////////////// //////////////////////////////////
// Start listening
//////////////////////////////////////// //////////////////////////////////
Sockaddr_in clientsocket;
Int Len = sizeof (sockaddr );
While (1)
{
Socket serconn = accept (sersocket, (sockaddr *) & clientsocket, & Len); // if it is not accept, it is conection .. It will constantly listen
Char sendbuf [100];
Sprintf (sendbuf, "Welcome % s to Bejing", inet_ntoa (clientsocket. sin_addr); // find the corresponding IP address and print this line to it
Send (serconn, sendbuf, strlen (sendbuf) + 1, 0 );
Char receivebuf [100]; // receives
Recv (serconn, receivebuf, strlen (receivebuf) + 1, 0 );
Printf ("% s \ n", receivebuf );
Closesocket (serconn); // close
Wsacleanup (); // actions to release resources
}
}
Client:
# Include <winsock2.h>
# Include <stdio. h>
# Pragma comment (Lib, "ws2_32.lib ")
Void main ()
{
Int err;
Word versionrequired;
Wsadata;
Versionrequired = makeword (1, 1 );
Err = wsastartup (versionrequired, & wsadata); // version information of the Protocol Library
If (! Err)
{
Printf ("the client nested word has been opened! \ N ");
}
Else
{
Printf ("An error occurred while opening the nested words on the client! \ N ");
Return; // end
}
Socket clientsocket = socket (af_inet, sock_stream, 0 );
Sockaddr_in clientsock_in;
Clientsock_in.sin_addr.s_un.s_addr = inet_addr ("127.0.0.1 ");
Clientsock_in.sin_family = af_inet;
Clientsock_in.sin_port = htons (6000 );
// BIND (clientsocket, (sockaddr *) & clientsock_in, strlen (sockaddr); // pay attention to the third parameter
// Listen (clientsocket, 5 );
Connect (clientsocket, (sockaddr *) & clientsock_in, sizeof (sockaddr); // start the connection
Char receivebuf [100];
Recv (clientsocket, receivebuf, 101,0 );
Printf ("% s \ n", receivebuf );
Send (clientsocket, "Hello, this is client", strlen ("Hello, this is client") + 1, 0 );
Closesocket (clientsocket );
Wsacleanup ();
}