多线程winsock2客户端/服务器应用程序 [英] Multithreaded winsock2 client/server application

查看:167
本文介绍了多线程winsock2客户端/服务器应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个winsock2客户端服务器应用程序,其中服务器应该是可以接受多个客户端的多线程.我是c ++的新手,使用单线程已完成.现在我想连接多个客户端.我非常多线程实现的新手.任何人都可以帮助我...........在此先感谢

这是我的一部分代码
:::::::::::::::::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::

I am developing a winsock2 client server application in which server should be a multithreaded that can accept multiple clients.I am new new to c++.Using single thread it is all done.Now i want to connect multiple clients.I am very new to multithreading implementation.Can any one help me........... thanks in advance

Here is my part of code
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

int					ErrorNo;
class FTP_Server
{
private:
   WSADATA              wsaData;
   SOCKET               ListeningSocket;
   SOCKET               NewConnection;
   SOCKADDR_IN          ServerAddr;
   SOCKADDR_IN          ClientAddr;
   char					SERVER_IP[16];
   char					U_Name[10];
   char					Password[40];
   char					C_U_Name[10];
   char					C_Password[10];
   int 					PORT_NO;
   int                  Len;
   char                 ReceiveBuf[1024];
   char                 BUFFER[1024];
   int                  BufLength;
  
   FILE					*READCONF;
   FILE					*SENDFILE;
   long					lSize;
   char                 PATH[100];
   WIN32_FIND_DATA		ffd;
   LARGE_INTEGER		filesize;
   TCHAR				szDir[MAX_PATH];
   size_t				length_of_arg;
   HANDLE				hFind ;
   DWORD				dwError;
   wchar_t				lpStr[1024];
   char					mbstr[1024];
   int					noOfFiles;
   char					*sharedFiles[50];
   map<string ,int>     CSOptions;
public:
	FTP_Server()
	{
		BufLength = 1024;
		Len = sizeof(ClientAddr);
		CSOptions["CommRequest"] = 1;
		CSOptions["getSharedFiles"] = 2 ;
		CSOptions["getPropFiles"] = 3;
		CSOptions["getFile"] = 4;
		CSOptions["EXIT"] = 5;
		
	}
   void ReadConfigurationFile(void);//reading configuration data from a file
   void CreateSocket(void); //socket creation 
   void BindSocket(void);//Bind and listen
   void AcceptClient(void);//Accept 
   int  AuthenticateClient(void);//authentication Uname Psss
   void AcceptRequest(void);//Incoming requests
   void CommunicationWithClients(void);
   void SendSharedFiles(void);
   void SendPropertiesOfFile(void);
   void SendFile(void);
   void CloseSockets(void);
   void CleanUp(void);
   void CommunicateWithClients(void);
   ~FTP_Server(){}
};

推荐答案

基本上,您需要在服务器端创建两个线程:一个正在侦听新连接,另一个正在与所有客户端通信. br/>
您需要支持所有客户端的列表/队列,并以循环方式与他们交谈.您确切发送和接收的内容取决于您的应用程序级别协议.因为您需要从两个线程中锁定对客户端列表的访问.使用Mutex(Windows上的关键部分"),或者使用多读者单作者锁(更好).

当客户端断开连接时,您需要捕获异常并安排客户端的远程套接字以将其删除.为了使其成为可能,您需要将每个通信周期都保留在try-catch块中,并在处理异常之后以周期重复通信.您可以处理例如客户端计算机由于任何原因而断电或关机的情况.您无法使用断开的电缆来处理这种情况.为此,可以使用超时.这是我对优美的"断开连接的看法:这是多余的.由于非优雅断开总是可能的,并且无论如何都应正确处理,因此不必担心优雅断开协议.

另请参阅我过去的答案:
C ++中的异常处理:未处理的异常:访问冲突 [来自同一端口号的多个客户端 [
Basically, you need to create two threads on server side: one listening to new connections, another one communicating with all the clients.

You need to support a list/queue of all clients and talk to them in a round-robin order. What exactly you send and receive depends on your application-level protocol. As you need to lock out the access to the list of clients from the two threads. Use Mutex (Critical Section on Windows) or, better yet, a multiple-readers, single-writer lock.

When a client is disconnected, you need to catch an exception and schedule the client''s remote socket for removal. To make it possible, you need to keep each communication cycle in try-catch block and repeat communication in cycle after the exception is handled. You can handle the situations when, for example, a client computer looses power or is shut down be any reason. You cannot handle the situation with disconnected cable. For this purpose, a timeout can work. This is my opinion about "graceful" disconnection: it is redundant. As non-graceful disconnection is always possible and should be properly handles anyway, there is no sense in bothering about graceful disconnection protocols.

See also my past answers:
Exception handling in C++: Unhandled Exception : Access Violation[^];
Networking with multiple clients (the answer is about .NET, but many ideas are similar): Multple clients from same port Number[^].

Worst thing you could do is dedicating a separate thread to each client. Actually, this is a well-known architectural mistake. It makes the system very unstable, as nobody knows how many clients will try to connect during run-time. Number of threads should be predictable and better be constant.

—SA


这篇关于多线程winsock2客户端/服务器应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆