From: http://hi.baidu.com/eternity8013/blog/item/86bf7503c557deea09fa932b.html
Function to be implemented: There is a console on the server sideProgram(Or Windows Service), which communicates with multiple client programs. The main thread has a socket bound to a fixed port and is responsible for listening to the socket information of the client. Every time a client program is started, the client sends a socket connection request, the server starts a new thread, and creates a socket in it to communicate with the socket of the client until the client program is closed, end the thread. The socket in the main thread is closed when the application exits.
Here is the server sideCodeShows how to create a multi-threaded socket server.
# Include "stdafx. H"
# Include <stdio. h>
DWORD winapi answerthread (lpvoid lparam)
{
Socket clientsocket = (socket) (lpvoid) lparam;
Int bytesrecv;
Char sendbuf [32] = "";
Char recvbuf [32] = "";
While (1)
{
Bytesrecv = socket_error;
For (INT I = 0; I <(INT) strlen (recvbuf); I ++)
{Recvbuf [I] = '\ 0 ';}
While (bytesrecv = socket_error)
{// Processing ing data
Bytesrecv = Recv (clientsocket, recvbuf, 32, 0 );
}
// Write your processing code here
Send (clientsocket, recvbuf, strlen (recvbuf), 0 );
Printf ("% s \ n", recvbuf );
}
Return 0;
}
Int main (INT argc, char * argv [])
{
// Initialize Winsock
Wsadata;
Int iret = wsastartup (makeword (2, 2), & wsadata );
If (iret! = No_error)
Printf ("error at wsastartup () \ n ");
// Create a socket
Socket m_socket;
M_socket = socket (af_inet, sock_stream, ipproto_tcp );
If (m_socket = invalid_socket)
{
Printf ("error at socket (): % LD \ n", wsagetlasterror ());
Wsacleanup ();
Return 0;
}
// bind a socket
sockaddr_in service;
service. sin_family = af_inet;
service. sin_addr.s_addr = inet_addr ("172.16.3.250");
service. sin_port = htons (2501);
If (BIND (m_socket, (sockaddr *) & service, sizeof (Service) = socket_error)
{< br> printf ("BIND () failed. \ n ");
closesocket (m_socket);
return 0;
}< br> else
printf (" bind OK. \ n ");
// Listen on a socket
If (Listen (m_socket, 20) = socket_error)
Printf ("error listening on socket. \ n ");
Else
Printf ("listening OK. \ n ");
// Accept a connection
Socket acceptsocket;
Printf ("waiting for a client to connect... \ n ");
While (1)
{
Acceptsocket = socket_error;
While (acceptsocket = socket_error)
{
Acceptsocket = accept (m_socket, null, null );
}
Printf ("Client Connected. \ n ");
DWORD dwthreadid;
Handle hthread;
Hthread = createthread (null, null, answerthread,
(Lpvoid) acceptsocket, 0, & dwthreadid );
If (hthread = NULL)
{
Printf ("creatthread answerthread () failed. \ n ");
}
Else
{
Printf ("createthread OK. \ n ");
}
}
Return 0;
}