⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tcpserverdlg.cpp

📁 winsock通讯
💻 CPP
字号:
// TCPServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TCPServer.h"
#include "TCPServerDlg.h"
#include "SetServerInfo.h"
#include <afxtempl.h>
#define CLIENTSENDINFO WM_USER+1001
#define BUFFERLEN 256

int index=0;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();
	
	// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA
	
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL
	
	// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTCPServerDlg dialog

CTCPServerDlg::CTCPServerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTCPServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTCPServerDlg)
	m_clientNo = 0;
	m_serverName = _T("");
	m_connectState = _T("");
	m_waitClientNo = 0;
	m_sendMessage = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTCPServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTCPServerDlg)
	DDX_Control(pDX, IDCANCEL, m_BtnCloseCtl);
	DDX_Control(pDX, IDC_BTNSEND, m_BtnSendctl);
	DDX_Control(pDX, IDC_SENDMESSAGE, m_sendMessageCtl);
	DDX_Control(pDX, IDC_CHATINFO, m_chatInfoCtl);
	DDX_Control(pDX, IDC_CLIENTSENDINFO, m_clientSendInfoCtl);
	DDX_Control(pDX, IDC_WAITCLIENTNO, m_waitClientNoCtl);
	DDX_Control(pDX, IDC_CLIENTNO, m_clientNoCtl);
	DDX_Control(pDX, IDC_CURRENTCONNECTSTATE, m_connectStateCtl);
	DDX_Text(pDX, IDC_CLIENTNO, m_clientNo);
	DDX_Text(pDX, IDC_SERVERNAME, m_serverName);
	DDX_Text(pDX, IDC_CURRENTCONNECTSTATE, m_connectState);
	DDX_Text(pDX, IDC_WAITCLIENTNO, m_waitClientNo);
	DDX_Text(pDX, IDC_SENDMESSAGE, m_sendMessage);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTCPServerDlg, CDialog)
//{{AFX_MSG_MAP(CTCPServerDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_RBUTTONDOWN()
ON_COMMAND(ID_CLOSE, OnClose)
ON_COMMAND(ID_RECEIVE, OnReceive)
ON_COMMAND(ID_SETPORT, OnSetport)
	ON_BN_CLICKED(IDC_BTNSEND, OnBtnsend)
	ON_LBN_DBLCLK(IDC_CHATINFO, OnDblclkChatinfo)
	//}}AFX_MSG_MAP
ON_MESSAGE(CLIENTSENDINFO,ReceiveData)

END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTCPServerDlg message handlers

BOOL CTCPServerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	
	// Add "About..." menu item to system menu.
	
	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);
	
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}
	
	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	m_serverConnectclient=socket(AF_INET,SOCK_STREAM,0);

	WSAAsyncSelect(m_serverConnectclient,m_hWnd,CLIENTSENDINFO,FD_WRITE|FD_READ|FD_ACCEPT|FD_CLOSE);
	m_setPortInfoBool=false;
	m_CollectSvr=false;
    m_client=0;
	numSock=0;
    CSetServerInfo setServerName;
	m_serverName=setServerName.m_hostName;
	UpdateData(false);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTCPServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTCPServerDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting
		
		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
		
		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;
		
		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTCPServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

BOOL CTCPServerDlg::PreTranslateMessage(MSG* pMsg) 
{
	// TODO: Add your specialized code here and/or call the base class
	//	if(pMsg->message=1000)
	//	{
	
	//	}
	
	return CDialog::PreTranslateMessage(pMsg);
}

void CTCPServerDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	
	CDialog::OnCancel();
}

void CTCPServerDlg::ReceiveData(UINT wParam,LONG lParam)
{
	sockaddr_in serveraddr;
    int serveraddrlen=sizeof(serveraddr);


	static int m_clientApplicationNo=0;
	static int m_waitForDone;

	CString info;
	int ClientNO;
	char buffer[BUFFERLEN];
//	MySock.SetSize(20);

	switch(LOWORD(lParam))
	{
	case  FD_ACCEPT:
		{
			m_client=accept((SOCKET)wParam,(SOCKADDR*)&serveraddr,&serveraddrlen);
			m_clientApplicationNo=m_clientApplicationNo+1;
			m_clientNo=m_clientApplicationNo;	
			info.Format("%d",m_clientNo);
			m_clientNoCtl.SetWindowText(info);
			m_connectStateCtl.SetWindowText("一客户端等待处理");
			
			if(INVALID_SOCKET==m_client)
			{
				m_connectState="连接失败";
				m_clientApplicationNo=m_clientApplicationNo-1;
				m_clientNo=m_clientApplicationNo;	
				info.Format("%d",m_clientNo);
				m_clientNoCtl.SetWindowText(info);
				m_connectStateCtl.SetWindowText("一客户端连接失败");
			}
			else
			{
                m_BtnCloseCtl.EnableWindow(FALSE);
				if(m_clientApplicationNo<=20)
				{
                    MySock.Add(m_client);
					m_waitClientNo=m_clientApplicationNo;
					info.Format("%d",m_waitClientNo);
			        m_waitClientNoCtl.SetWindowText(info);
				}
			    if(m_clientApplicationNo>20)
				{
				   int i;
                   for(i=0;i<MySock.GetSize();i++)
				   {
					   if(0==MySock.GetAt(i))
					   {
                          MySock.InsertAt(i,m_client);
						  m_waitClientNo=m_clientApplicationNo;
						  info.Format("%d",m_waitClientNo);
			              m_waitClientNoCtl.SetWindowText(info);
						   break;
					   }
				   }
				   if(MySock.GetSize()-1==i)
				   {
					   AfxMessageBox("服务器连接忙,无法连接",MB_USERDEFINE);
				   }
				}
			}

			m_CollectSvr=true;			
			break;
		}
	case FD_READ:
		{
			int No; 
			m_connectStateCtl.SetWindowText("客户端开始处理");
			int PackLen=recv((SOCKET)wParam,buffer,BUFFERLEN,0); 
			for( No=0;No<=MySock.GetSize( );No++)
			{
				if(MySock.GetAt(No)==wParam)
				{ 
					No++;
					ClientNO=No;
					break;
				}

			}

			if(PackLen>0)
			{
				buffer[PackLen]=0;
			    info.Format("%d%s",ClientNO,buffer);
				m_clientSendInfoCtl.SetWindowText(info);
				m_chatInfoCtl.InsertString(index,info);	
				index++;
			}
			else
			{
				m_clientSendInfoCtl.SetWindowText("客户端没有数据发送");
			}
			
			break;
		}
	case FD_WRITE:
		{
			UpdateData();
			m_connectStateCtl.SetWindowText("一客户端正在处理");
			if(m_sendMessage.IsEmpty())
			{
				if(MB_OK==AfxMessageBox("确定要发送空消息!"))
				{
					info.Format("服务器端说:%s",m_sendMessage) ;				  
					if(SOCKET_ERROR==send((SOCKET)wParam,info.GetBuffer(0),info.GetLength(),0))
					{
						AfxMessageBox("发送失败请重新输入!",MB_USERDEFINE); 
						m_sendMessageCtl.SetFocus();
						
					}
					else
					{
						m_chatInfoCtl.InsertString(index,info);
						index++;
					}					
				}
				else
				{
					m_sendMessageCtl.SetFocus();
				}
			}
			else
			{
				
				info.Format("服务器端说:%s",m_sendMessage) ;				  
				send((SOCKET)wParam,info.GetBuffer(0),info.GetLength(),0);
				m_chatInfoCtl.InsertString(index,info);
				index++;
				m_sendMessageCtl.SetWindowText(" ");
				m_sendMessageCtl.SetFocus();
			}
			
			
			break;
		}
	case FD_CLOSE:
		{
			m_clientApplicationNo=m_clientApplicationNo-1;
			m_clientNo=m_clientApplicationNo;	
			info.Format("%d",m_clientNo);
			m_clientNoCtl.SetWindowText(info);
			
			m_waitClientNo=m_clientApplicationNo;
			info.Format("%d",m_waitClientNo);
			m_waitClientNoCtl.SetWindowText(info);
			
			m_connectStateCtl.SetWindowText("一客户端结束处理");
			for(int j=0;j<MySock.GetSize();j++)
			{
                if(MySock.GetAt(j)==wParam)
				{
					int temp=j+1;
					info.Format("%d%s",temp,"号客户端关闭");
					m_chatInfoCtl.InsertString(index,info);
					index++;
					MySock.RemoveAt(j);
                    wParam=0;
					MySock.InsertAt(j,wParam);
				}
			}
			int ClientConnectNumber=0;
			for(int i=0;i<MySock.GetSize();i++)
			{
				if(0==MySock.GetAt(i))
				ClientConnectNumber++;
			}
			if(ClientConnectNumber==MySock.GetSize())
			{
				m_BtnCloseCtl.EnableWindow(TRUE);
			}

				
				break;
		}
	default:
		break;		
	}
	
}

void CTCPServerDlg::OnRButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CMenu oMenu;
	if (oMenu.LoadMenu(IDR_SETSRVOPTION))        
	{
		CMenu* pPopup = oMenu.GetSubMenu(0);
		ASSERT(pPopup != NULL);
		
		if(m_CollectSvr)
		{
			pPopup->ModifyMenu(ID_CLOSE,MF_BYCOMMAND,ID_CLOSE,"关闭服务器");
			//	pPopup->ModifyMenu(ID_SETPORT,MF_GRAYED,ID_SETPORT,"端口设置");
			pPopup->ModifyMenu(ID_SETPORT,MF_BYCOMMAND,ID_SETPORT,"端口设置");
			pPopup->ModifyMenu(ID_RECEIVE,MF_GRAYED,ID_RECEIVE,"开启服务器");
			
			
		}
		if(m_setPortInfoBool)
		{
			pPopup->ModifyMenu(ID_CLOSE,MF_GRAYED,ID_CLOSE,"关闭服务器");
			//	pPopup->ModifyMenu(ID_SETPORT,MF_GRAYED,ID_SETPORT,"端口设置");
			pPopup->ModifyMenu(ID_SETPORT,MF_BYCOMMAND,ID_SETPORT,"端口设置");
			pPopup->ModifyMenu(ID_RECEIVE,MF_BYCOMMAND,ID_RECEIVE,"开启服务器");
		}
		if(!m_setPortInfoBool)
		{
			pPopup->ModifyMenu(ID_CLOSE,MF_GRAYED,ID_CLOSE,"关闭服务器");
			pPopup->ModifyMenu(ID_SETPORT,MF_BYCOMMAND,ID_SETPORT,"端口设置");
			pPopup->ModifyMenu(ID_RECEIVE,MF_GRAYED,ID_RECEIVE,"开启服务器");
		}
		
		
		
		CPoint oPoint;//定义一个用于确定光标位置的位置
		// 确定鼠标位置以便在该位置附近显示菜单
		GetCursorPos( &oPoint);//获取当前光标的位置,以便使得菜单可以跟随光标
		SetForegroundWindow();
		pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,oPoint.x, oPoint.y, this); 
	}
	CDialog::OnRButtonDown(nFlags, point);
}

void CTCPServerDlg::OnClose() 
{
	// TODO: Add your command handler code here
	m_setPortInfoBool=false;
	m_CollectSvr=false;
	int index=0;
//     if(int i=0;i<MySock.GetSize();i++)
// 	{
// 		if(0==MySock.GetAt(i))
// 			index++;
// 	}
//     if(index==MySock.GetSize())
// 	{
//       
// 	}
// 	else

	
}

void CTCPServerDlg::OnReceive() 
{
	// TODO: Add your command handler code here
	
    int  port1;
	CString strIP;
	port1=m_Port1;
	strIP=m_setIp;
    CString  info1,info2;
    info1.Format("%s","服务器端口绑定成功>>>>>>>>");
    
    info2.Format("%s","服务器开始监听>>>>>>>>>>>>");
	
    serverAddr.sin_family=AF_INET;

//	serverAddr.sin_addr.S_un.S_addr=inet_addr(strIP);
    
	
    serverAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
	
	serverAddr.sin_port=htons(port1);
    if(bind(m_serverConnectclient,(LPSOCKADDR)&serverAddr,sizeof(serverAddr))==SOCKET_ERROR)
	{
		LPVOID lpMsgBuf; //Windows will allocate 
		::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,0, GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //默认语言
			(LPTSTR)&lpMsgBuf, 0, NULL );
		
		//显示
		::MessageBox(0, (LPCTSTR)lpMsgBuf, _T("GetLastError"), MB_OK|MB_ICONINFORMATION );
		//lpMsgBuf中是你要的错误提示.
		
		//释放内存
		::LocalFree( lpMsgBuf );
		
		
	}
	else
	{
	m_chatInfoCtl.InsertString(index,info1);
	index++;
	}
    
    
	if(listen(m_serverConnectclient,SOMAXCONN)==SOCKET_ERROR)
	{
		LPVOID lpMsgBuf; //Windows will allocate 
		::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,0, GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //默认语言
			(LPTSTR)&lpMsgBuf, 0, NULL );
		
		//显示
		::MessageBox(0, (LPCTSTR)lpMsgBuf, _T("GetLastError"), MB_OK|MB_ICONINFORMATION );
		//lpMsgBuf中是你要的错误提示.
		
		//释放内存
		::LocalFree( lpMsgBuf );
	}
	else
	{
	m_chatInfoCtl.InsertString(index,info2);
	index++;
	}
	
	
}

void CTCPServerDlg::OnSetport() 
{
	// TODO: Add your command handler code here
	CSetServerInfo dlg;
	if(IDOK==dlg.DoModal())
	{
		m_Port1 = dlg.ReturnPort1();
		m_setIp=dlg.ReturnIP();
		m_setPortInfoBool=TRUE;
	}
	
}

void CTCPServerDlg::OnBtnsend() 
{
	// TODO: Add your control notification handler code here
   if(0==numSock)
   {
	   AfxMessageBox("请选择要回复的记录",MB_USERDEFINE);
	   m_sendMessageCtl.SetFocus();
   }
   else
   {

	   PostMessage(CLIENTSENDINFO,numSock,FD_WRITE);
   }

//	::PostMessage(m_hWnd,CLIENTSENDINFO,0,FD_WRITE);//这种方法也可以

}

void CTCPServerDlg::OnDblclkChatinfo() 
{
	// TODO: Add your control notification handler code here
 

	int index=m_chatInfoCtl.GetCurSel();
	int i;
	CString ClientInfo,strReply,FindClinet,strNO;
    FindClinet="客户";

	m_chatInfoCtl.GetText(index,ClientInfo);

	for(i=1;i<=MySock.GetSize();i++)
    {
		strNO.Format("%d",i);
		int p=ClientInfo.Find("客户");
		int p1=ClientInfo.Find(strNO);
		if(-1!=ClientInfo.Find("客户")&&-1!=ClientInfo.Find(strNO))
		{

			numSock=MySock.GetAt(i-1);
			break;
		}
    }
	m_sendMessage=" ";
	UpdateData(false);
	m_sendMessageCtl.SetFocus();


    
    
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -