Implement server-side multi-threaded Socket Server

xiaoxiao2021-03-06  104

Want to implement: There is a console program (or Windows service) on the server side, communicating with multiple client program, where the main thread has a socket binding on a fixed port, responsible for listening to the client's socket information. Whenever a client program is activated, the client sends a Socket connection request, and the Server is newly turned on and creates a socket communication with the client's socket communication until the client program is turned off, ending the thread. The Socket in the main thread is turned off when the application exits.

Here is a simple schematic of Server end code, showing how to create multithreaded socket server.

#include "StdAfx.h" #include 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) {// receiving 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 Wsadata; IrgeT = 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 = h TONS (2501); if (Bind (m_socket, (sockaddr *) & service, sizeof (service)) == SOCKET_ERROR) {Printf ("Bind () failed./n"); closesocket (m_socket); return 0;} 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;} Socket client program is very simple, you can use VB to drag a Winsock control to Form, then connect to the server's socket and send data.

转载请注明原文地址:https://www.9cbs.com/read-122944.html

New Post(0)