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

📄 chatserverdlg.cpp

📁 visual c++ 实例编程
💻 CPP
字号:
// ChatServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ChatServer.h"
#include "ChatServerDlg.h"
#include <afxmt.h>

#define PORT1 (u_short)56790
#define PORT2 (u_short)56791
#define NO_FLAGS_SET 0
#define MAXBUFLEN 5025

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

CMutex m_mutex;
send_info info_data;		//全局参数
CList<socket_info,socket_info&>s_info;
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
////////////////////////////senddata///////////////////////////////////////////
void closesocketlink(void *s)
{
	SOCKET clientSocket=(SOCKET)s;
	int status=shutdown(clientSocket, 2);
    if (status == SOCKET_ERROR)
		 AfxMessageBox("ERROR: shutdown unsuccessful!",MB_OK);

  /* close the socket */
    status=closesocket(clientSocket);
    if (status == SOCKET_ERROR)
		AfxMessageBox("ERROR: closesocket unsuccessful!",MB_OK);
}
UINT SendData(void* cs)
{
	int numsnd;
	SOCKET clientSocket=(SOCKET)cs;
	CWinThread* now;

	while(1)
	{
		if(info_data.data!="Close!")
		{
			m_mutex.Lock();
			numsnd=send(clientSocket,info_data.data,info_data.data.GetLength(),NO_FLAGS_SET);
			if(numsnd==SOCKET_ERROR||numsnd==0)
			{
				AfxMessageBox("传输失败",MB_OK);
				break;
			}
			now=info_data.thread;
			m_mutex.Unlock();
			now->SuspendThread();
		}
		else
		{
			goto bb;
		}
	}
bb:	closesocketlink((LPVOID)clientSocket);
	AfxEndThread(0,true);
	return 1;
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////recvdata///////////////////////////////////////////
UINT RecvData(void* cs)
{
	char buffer[MAXBUFLEN];
	int numrcv;
	SOCKET clientSocket=(SOCKET)cs;
	while(1)
	{
		numrcv=recv(clientSocket, buffer, MAXBUFLEN, NO_FLAGS_SET);
		if ((numrcv == 0) || (numrcv == SOCKET_ERROR))
		{
			AfxMessageBox("Connection terminated!",MB_OK);
			break;
		}
		buffer[numrcv]='\0';
		if(strcmp(buffer,"Close!")!=0)
		{
		char petname[20];
		char *pos=strchr(buffer,':');
		int len_buf=strlen(buffer);
		int len_pos=strlen(pos);
		pos+=1;
		int len=len_buf-len_pos;
		for(int i=0;i<len;i++)
			petname[i]=buffer[i];
		petname[len]='\0';
		POSITION po=s_info.GetHeadPosition();
		socket_info s1;
		int count=s_info.GetCount();
		for(i=0;i<count;i++)
		{
			if(po!=NULL)
			{
				s1=s_info.GetNext(po);
				if(s1.pet.Compare(petname)==0)
				{
					m_mutex.Lock();
					info_data.data=pos;
					info_data.thread=s1.thread;
					m_mutex.Unlock();
				}
				s1.thread->ResumeThread();
				break;
			}
				//else,用户不在线;
		}
		}
		else
		{
			POSITION po=s_info.GetHeadPosition();
			POSITION po1;
			socket_info s1;
			int count=s_info.GetCount();
			for(int i=0;i<count;i++)
			{
				if(po!=NULL)
				{
					po1=po;
					s1=s_info.GetNext(po);
					if(clientSocket==s1.s_client)
					{
						m_mutex.Lock();
						info_data.data=buffer;
						m_mutex.Unlock();
						s1.thread->ResumeThread();
						s_info.RemoveAt(po1);
						break;
					}
				}
			}
			goto aa;
		}
	}
aa:	closesocketlink((LPVOID)clientSocket);
	AfxEndThread(0,true);
	return 1;
}

////////////////////////////////////////////////////////////////////////////////
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()

/////////////////////////////////////////////////////////////////////////////
// CChatServerDlg dialog

CChatServerDlg::CChatServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CChatServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CChatServerDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CChatServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CChatServerDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CChatServerDlg, CDialog)
	//{{AFX_MSG_MAP(CChatServerDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_CHAT, OnChat)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChatServerDlg message handlers

BOOL CChatServerDlg::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
	Init_net(PORT1);
//	Init_net(PORT2);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CChatServerDlg::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 CChatServerDlg::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 CChatServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

BOOL CChatServerDlg::Init_net(u_short PORT)
{
////////////////////////////网络初始化////////////////////////////////////////
	addrLen=sizeof(SOCKADDR_IN);
	status=WSAStartup(MAKEWORD(1, 1), &Data);
	if (status != 0)
	{
		MessageBox("ERROR: WSAStartup unsuccessful!","网络飞标",MB_OK);
		return  false;
	}

	memset(&serverSockAddr, 0, sizeof(serverSockAddr));
    serverSockAddr.sin_port=htons(PORT);
    serverSockAddr.sin_family=AF_INET;
    serverSockAddr.sin_addr.s_addr=htonl(INADDR_ANY);

    serverSocket=socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == INVALID_SOCKET)
	{
		MessageBox("socket unsuccessful!","网络飞标",MB_OK);
		status=WSACleanup();
		if (status == SOCKET_ERROR)
			 MessageBox("ERROR: WSACleanup unsuccessful!","网络飞标",MB_OK); 
		return false;
	}

    status=bind(serverSocket, (LPSOCKADDR) &serverSockAddr, sizeof(serverSockAddr));
    if (status == SOCKET_ERROR)
	{
		MessageBox("ERROR: bind unsuccessful!","网络飞标",MB_OK);
		return false;
	}

	status=listen(serverSocket, 5);
	if (status == SOCKET_ERROR)
	{
		MessageBox("ERROR: listen unsuccessful!","网络飞标",MB_OK);
		return false;
	}
//////////////////////////////////////////////////////////////////////////////
	return true;
}

void CChatServerDlg::Chat()
{
	char buffer[MAXBUFLEN];
	int numrcv;
	while(1)
	{
		CWinThread *hHandle_s,*hHandle_r;
		clientSocket=accept(serverSocket,(LPSOCKADDR) &clientSockAddr, &addrLen);
		numrcv=recv(clientSocket,buffer,MAXBUFLEN, NO_FLAGS_SET);
		buffer[numrcv]='\0';

		hHandle_s=AfxBeginThread(SendData,(LPVOID)clientSocket);
/*		hHandle_s=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)SendData,
				      (LPVOID)clientSocket,CREATE_SUSPENDED,&threadID);*/
		hHandle_s->SuspendThread();

		socket_info info;
		info.client_addr=clientSockAddr.sin_addr.s_addr;
		info.s_client=clientSocket;
		info.pet=buffer;
		info.thread=hHandle_s;
		s_info.AddTail(info);

		hHandle_r=AfxBeginThread(RecvData,(LPVOID)clientSocket);
/*		hHandle_r=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)RecvData,
				      (LPVOID)clientSocket,0,&threadID);*/
		if (hHandle_s ==NULL&&hHandle_r==NULL)
		{
			MessageBox("ERROR: Unable to create thread!","网络飞标",MB_OK);
			status=closesocket(clientSocket);
			if (status == SOCKET_ERROR)
				MessageBox("ERROR: closesocket unsuccessful!","网络飞标",MB_OK);
		}
	}
}

void CChatServerDlg::OnChat() 
{
	// TODO: Add your control notification handler code here
	Chat();
}

⌨️ 快捷键说明

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