Implementation of multi-threaded concurrent communication based on socket under Windows

Source: Internet
Author: User
Tags htons

This paper introduces the communication mechanism of socket socket based on TCP/IP protocol under Windows operating system and the knowledge and skill of multithreading programming, and gives a detailed algorithm of multi-threading method to implement concurrent communication model of multi-user and Server (c/s), finally shows the C + + An application instance written for multi-user and server communication is attached to the program.

Keywords:Windows; sockets; multithreading; concurrent servers;

Socket is a socket specification based on the Transport Layer Protocol (mainly TCP and UDP), originally proposed by the University of California, Berkley, to develop a network communication interface for UNIX systems, which defines the specification of communication between two computers, socket Shielding the underlying communication software and specific operating system differences, so that any two installed TCP protocol software and the implementation of the socket specification of the communication between the computer is possible, the socket interface is the most common TCP/IP network application interface, but also in the Internet The most common api[1 for network application development, this paper introduces the basic mechanism of socket communication and the basic principle of using multithreading technology to realize concurrent communication, and gives an example.

All code See: http://download.csdn.net/detail/xy010902100449/8570623

-----------------------------------------------------------------------------------//Copyright scut4009 All//--------- --------------------------------------------------------------------------//File name: socketsever.cpp//Author: zp1015// Write Time: 2015/04/7//Compilation tool: Visual Studio 2008//Program Description: Socket multithreaded communication, server side, based on tcp//------------------------------------------ ------------------------------------------#include "stdafx.h" #include "Socket.h" #include <windows.h>handle hmutex;//------------------------------------------------------------------------------------//Function name: Send ( Socket sockclient)/* Function: Send data/* entry parameter: SOCKET sockclient//Export parameter://global variable Reference://Call module: none//---------------- --------------------------------------------------------------------*/void Send (SOCKET sockclient) {char sendbuf[ Maxsize];int byte = 0;while (1) {WaitForSingleObject (Hmutex, INFINITE); gets (sendbuf); byte= Send (Sockclient,sendbuf, Strlen (SENDBUF) +1,0);;/ /server accepts data from client if (byte<=0) {break;} Sleep (1000); ReleaseMutex (Hmutex);} Closesocket (sockclient);//close socket, once communication is complete}//------------------------------------------------------------------ ------------------//Function Name: REC ()/* Function function: receive function/* entry parameter: SOCKET sockclient//Export parameter://global variable Reference://Call module: No//- -----------------------------------------------------------------------------------*/void Rec (SOCKET sockclient) {char Revbuf[maxsize];int byte = 0;while (1) {WaitForSingleObject (Hmutex, INFINITE); byte= recv (Sockclient,revbuf, Strlen (REVBUF) +1,0);//The server accepts data from the client if (byte<=0) {break;} printf ("%s\n", revbuf); Sleep (1000); ReleaseMutex (Hmutex);} Closesocket (sockclient);//close socket, one communication complete}//****************************************************************** * * Function Name * * Main ()//** input * * No//** output * * No//** function Description * * Main function//********************* /int Main () {sockaddr_in  Addrserver;int Sockserver; if (Socket_error ==socketinit ()) {return-1;} Addrserver.sin_adDr. S_un. S_addr=htonl (inaddr_any);//htol converts host byte-order long to network byte-order addrserver.sin_family=af_inet;addrserver.sin_port=htons (6666 //htos is used to convert the port into characters, more than 1024 of the number can be Sockserver=socket (af_inet,sock_stream,0);//connection-oriented reliability service Sock_strambind (Sockserver, ( sockaddr*) &addrserver,sizeof (sockaddr));//Bind the socket to the corresponding address and port listen (sockserver,5);//The maximum length in the wait queue is 5printf (" Welcome,the Host%s is running! Now wating for someone comes In!\n ", Inet_ntoa (ADDRSERVER.SIN_ADDR)); int len=sizeof (SOCKADDR); Sockaddr_in Addrclient;while (1) {SOCKET sockclient=accept (sockserver, (sockaddr*) &addrclient,&len);// Block the calling process until a new connection occurs if (sockclient = = Invalid_socket) {printf ("Accept failed!\n"); continue;//Continue listening}handle HThread1 = CreateThread (null,0, (lpthread_start_routine) send, (LPVOID) sockclient,0,0);//Send if (hthread1!=null) {CloseHandle ( HTHREAD1);} HANDLE hThread2 = CreateThread (null,0, (Lpthread_start_routine) Rec, (LPVOID) sockclient,0,0);//Receive if (Hthread2!=null) { CloseHandle (hThread2);} Sleep (1000);//Must be}getchar (); return 0;}
-----------------------------------------------------------------------------------//Copyright scut4009 All//--------- --------------------------------------------------------------------------//File name: socketclient.cpp//Author: zp1015// Write Time: 2015/04/7//Compilation tool: Visual Studio 2008//Program Description: Socket multithreaded communication//----------------------------------------------------- -------------------------------#include "stdafx.h" #include "Socket.h" #pragma comment (lib, "Ws2_32.lib") const char * Severip = "192.168.1.100"; HANDLE hmutex;//------------------------------------------------------------------------------------//function name: Send (socket sockclient)/* Function: Send data/* entry parameter: SOCKET sockclient//Export parameter://global variable Reference://Call module: none//--------------- ---------------------------------------------------------------------*/void Send (SOCKET sockclient) {char sendbuf[ Maxsize];int byte = 0;while (1) {WaitForSingleObject (Hmutex, INFINITE); gets (sendbuf); byte= Send (Sockclient,sendbuf, Strlen (SENDBUF) +1,0);;/ /server accepts data from client if (byte<=0) {breAK;} Sleep (1000); ReleaseMutex (Hmutex);} Closesocket (sockclient);//close socket, once communication is complete}//------------------------------------------------------------------ ------------------//Function Name: REC ()/* Function function: receive function/* entry parameter: SOCKET sockclient//Export parameter://global variable Reference://Call module: No//- -----------------------------------------------------------------------------------*/void Rec (SOCKET sockclient) {char Revbuf[maxsize];int byte = 0;while (1) {WaitForSingleObject (Hmutex, INFINITE); byte= recv (Sockclient,revbuf, Strlen (REVBUF) +1,0);//The server accepts data from the client if (byte<=0) {break;} printf ("%s\n", revbuf); Sleep (1000); ReleaseMutex (Hmutex);} Closesocket (sockclient);//Close SOCKET, once communication is complete}int main () {if (Socket_error ==socketinit ()) {return-1;} while (1) {SOCKET sockclient=socket (af_inet,sock_stream,0); Sockaddr_in addrsrv;addrsrv.sin_addr. S_un. S_ADDR=INET_ADDR (Severip);//Set the IP address of the server that needs to be connected addrsrv.sin_family=af_inet;addrsrv.sin_port=htons (6666);// Set the port address of the server you want to connect to connect (sockclient, (sockaddr*) &addrsrv,sizeof (sockaddr));//Connect to server handle HthreAd1 = CreateThread (null,0, (Lpthread_start_routine) Rec, (LPVOID) sockclient,0,0), if (hthread1!=null) {CloseHandle ( HTHREAD1);} HANDLE hThread2 = CreateThread (null,0, (Lpthread_start_routine) Send, (LPVOID) sockclient,0,0); if (hthread2!=null) { CloseHandle (hThread2);} Sleep (1000);}    GetChar (); WSACleanup (); return-1;}



Implementation of multi-threaded concurrent communication based on socket under Windows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.