基于套接字的网络聊天系统

VC++6.0制作一个MFC的对话框程序


一、制作客户端:命名为Client

1、Client.cpp:

// Client.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "Client.h"
#include "ClientDlg.h"

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

/
// CClientApp

BEGIN_MESSAGE_MAP(CClientApp, CWinApp)
 //{{AFX_MSG_MAP(CClientApp)
  // NOTE - the ClassWizard will add and remove mapping macros here.
  //    DO NOT EDIT what you see in these blocks of generated code!
 //}}AFX_MSG
 ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/
// CClientApp construction

CClientApp::CClientApp()
{
 // TODO: add construction code here,
 // Place all significant initialization in InitInstance
}

/
// The one and only CClientApp object

CClientApp theApp;

/
// CClientApp initialization

BOOL CClientApp::InitInstance()
{
 AfxEnableControlContainer();

 // Standard initialization
 // If you are not using these features and wish to reduce the size
 //  of your final executable, you should remove from the following
 //  the specific initialization routines you do not need.

#ifdef _AFXDLL
 Enable3dControls();   // Call this when using MFC in a shared DLL
#else
 Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif

 WSADATA wsd; 
    WSAStartup(MAKEWORD(2,2),&wsd); 
 
    CClientDlg dlg; 
    m_pMainWnd = &dlg; 

 int nResponse = dlg.DoModal();
 if (nResponse == IDOK)
 {
  // TODO: Place code here to handle when the dialog is
  //  dismissed with OK
 }
 else if (nResponse == IDCANCEL)
 {
  // TODO: Place code here to handle when the dialog is
  //  dismissed with Cancel
 }


 // Since the dialog has been closed, return FALSE so that we exit the
 //  application, rather than start the application's message pump.
 return FALSE;
}

int CClientApp::ExitInstance()
{
 // TODO: Add your specialized code here and/or call the base class
 WSACleanup();
 return CWinApp::ExitInstance();
}

2、Client.h:

// Client.h : main header file for the CLIENT application
//

#if !defined(AFX_CLIENT_H__E1A7E768_0B18_4D3B_8299_F51A19B0622F__INCLUDED_)
#define AFX_CLIENT_H__E1A7E768_0B18_4D3B_8299_F51A19B0622F__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#ifndef __AFXWIN_H__
 #error include 'stdafx.h' before including this file for PCH
#endif

#include "resource.h"  // main symbols

/
// CClientApp:
// See Client.cpp for the implementation of this class
//

class CClientApp : public CWinApp
{
public:
 CClientApp();

// Overrides
 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(CClientApp)
 public:
 virtual BOOL InitInstance();
 virtual int ExitInstance();
 //}}AFX_VIRTUAL

// Implementation

 //{{AFX_MSG(CClientApp)
  // NOTE - the ClassWizard will add and remove member functions here.
  //    DO NOT EDIT what you see in these blocks of generated code !
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};


/

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_CLIENT_H__E1A7E768_0B18_4D3B_8299_F51A19B0622F__INCLUDED_)

3、ClientDlg.cpp:

// ClientDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Client.h"
#include "ClientDlg.h"

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

/
// CClientDlg dialog

CClientDlg::CClientDlg(CWnd* pParent /*=NULL*/)
 : CDialog(CClientDlg::IDD, pParent)
{
 //{{AFX_DATA_INIT(CClientDlg)
 //}}AFX_DATA_INIT
 // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CClientDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{{AFX_DATA_MAP(CClientDlg)
 DDX_Control(pDX, IDC_EDIT4, m_SendData);
 DDX_Control(pDX, IDC_LIST2, m_MsgList);
 DDX_Control(pDX, IDC_EDIT3, m_NickName);
 DDX_Control(pDX, IDC_EDIT2, m_ServerPort);
 DDX_Control(pDX, IDC_EDIT1, m_ServerIP);
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CClientDlg, CDialog)
 //{{AFX_MSG_MAP(CClientDlg)
 ON_WM_SYSCOMMAND()
 ON_WM_PAINT()
 ON_WM_QUERYDRAGICON()
 ON_BN_CLICKED(IDC_BUTTON1, OnLogin)
 ON_MESSAGE(CM_RECEIVE,ReceiveInfo)
 ON_BN_CLICKED(IDC_BUTTON2, OnSend)
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/
// CClientDlg message handlers

BOOL CClientDlg::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_SockClient = socket(AF_INET,SOCK_STREAM,0);
 return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CClientDlg::ReceiveInfo()
{
 char buffer[1024];
 int num=recv(m_SockClient,buffer,1024,0);        //接收数据
 buffer[num]=0;                                   //定义结束标记
 m_MsgList.AddString(buffer); 
}

void CClientDlg::OnLogin()
{
 // TODO: Add your control notification handler code here
  // TODO: Add your control notification handler code here
 sockaddr_in serveraddr;
 CString strport;
 m_ServerPort.GetWindowText(strport);
 m_ServerIP.GetWindowText(m_IP);
 if(strport.IsEmpty()||m_IP.IsEmpty())
 {
  MessageBox("请设置服务器IP和端口号");
  return;
 }
 m_Port=atoi(strport);
 serveraddr.sin_family=AF_INET;
 serveraddr.sin_port=htons(m_Port);
 serveraddr.sin_addr.S_un.S_addr=inet_addr(m_IP);      //设置服务器IP
 //开始连接服务器
    if (connect(m_SockClient,(sockaddr*)&serveraddr,sizeof(serveraddr))!=0) 
 {
  MessageBox("连接失败!");
  return;
 }
 else
  MessageBox("连接成功!");
 WSAAsyncSelect(m_SockClient,m_hWnd,1000,FD_READ);
 CString strname,info;
 m_NickName.GetWindowText(strname);
 info.Format("%s------>%s",strname,"进入聊天室");
 send(m_SockClient,info.GetBuffer(0),info.GetLength(),0);

}

void CClientDlg::OnSend()
{
 CString strData,name,info ; 
 m_NickName.GetWindowText(name);
 m_SendData.GetWindowText(strData); 
 if (!name.IsEmpty() && !strData.IsEmpty()) 
    { 
        info.Format("%s说: %s",name,strData); 
        //开始发送数据 
        send(m_SockClient,info.GetBuffer(0),info.GetLength(),0);     
        m_MsgList.AddString(info); 
        m_SendData.SetWindowText(""); 
    }    

}
4、ClientDlg.h:


#if !defined(AFX_CLIENTDLG_H__AB03175A_736A_4B39_875F_D389116DF842__INCLUDED_)
#define AFX_CLIENTDLG_H__AB03175A_736A_4B39_875F_D389116DF842__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

/
// CClientDlg dialog
#include "winsock2.h"
#pragma comment (lib,"ws2_32.lib")
#define CM_RECEIVE 1000

class CClientDlg : public CDialog
{
// Construction
public:
 void ReceiveInfo();
 CClientDlg(CWnd* pParent = NULL); // standard constructor
 SOCKET   m_SockClient;
 UINT     m_Port;
 CString  m_IP;
// Dialog Data
 //{{AFX_DATA(CClientDlg)
 enum { IDD = IDD_CLIENT_DIALOG };
 CListBox m_MsgList;
 CEdit m_ServerPort;
 CEdit m_ServerIP;
 CEdit m_SendData;
 CEdit m_NickName;
 //}}AFX_DATA

 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(CClientDlg)
 protected:
 virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support

 //}}AFX_VIRTUAL

// Implementation
protected:
 HICON m_hIcon;

 // Generated message map functions
 //{{AFX_MSG(CClientDlg)
 virtual BOOL OnInitDialog();
 afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
 afx_msg void OnPaint();
 afx_msg HCURSOR OnQueryDragIcon();
 afx_msg void OnLogin();
 afx_msg void OnSend();
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_CLIENTDLG_H__AB03175A_736A_4B39_875F_D389116DF842__INCLUDED_)</span>
5、Resource.h:

//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by Client.rc
//
#define IDM_ABOUTBOX                    0x0010
#define IDD_ABOUTBOX                    100
#define IDS_ABOUTBOX                    101
#define IDD_CLIENT_DIALOG               102
#define IDR_MAINFRAME                   128
#define IDC_EDIT1                       1000
#define IDC_EDIT2                       1001
#define IDC_EDIT3                       1002
#define IDC_BUTTON1                     1003
#define IDC_EDIT4                       1005
#define IDC_BUTTON2                     1006
#define IDC_LIST2                       1007

// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE        129
#define _APS_NEXT_COMMAND_VALUE         32771
#define _APS_NEXT_CONTROL_VALUE         1008
#define _APS_NEXT_SYMED_VALUE           101
#endif
#endif
6、Stdafx.h:

// stdafx.h : include file for standard system include files,
//  or project specific include files that are used frequently, but
//      are changed infrequently
//

#if !defined(AFX_STDAFX_H__91CBAAA4_9EED_4573_8ACE_9439037A3130__INCLUDED_)
#define AFX_STDAFX_H__91CBAAA4_9EED_4573_8ACE_9439037A3130__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define VC_EXTRALEAN  // Exclude rarely-used stuff from Windows headers

#include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions
#include <afxdisp.h>        // MFC Automation classes
#include <afxdtctl.h>  // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>   // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT


//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_STDAFX_H__91CBAAA4_9EED_4573_8ACE_9439037A3130__INCLUDED_)
7、stdafx.cpp:

// stdafx.cpp : source file that includes just the standard includes
// Client.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"


二、制作服务器端:命名为Server

1、Server.cpp:

// Server.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "Server.h"
#include "ServerDlg.h"

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

/
// CServerApp

BEGIN_MESSAGE_MAP(CServerApp, CWinApp)
 //{{AFX_MSG_MAP(CServerApp)
  // NOTE - the ClassWizard will add and remove mapping macros here.
  //    DO NOT EDIT what you see in these blocks of generated code!
 //}}AFX_MSG
 ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/
// CServerApp construction

CServerApp::CServerApp()
{
 // TODO: add construction code here,
 // Place all significant initialization in InitInstance
}

/
// The one and only CServerApp object

CServerApp theApp;

/
// CServerApp initialization

BOOL CServerApp::InitInstance()
{
 AfxEnableControlContainer();

 // Standard initialization
 // If you are not using these features and wish to reduce the size
 //  of your final executable, you should remove from the following
 //  the specific initialization routines you do not need.

#ifdef _AFXDLL
 Enable3dControls();   // Call this when using MFC in a shared DLL
#else
 Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif

 WSADATA wsd;
 WSAStartup(MAKEWORD(2,2),&wsd);

 CServerDlg dlg;
 m_pMainWnd = &dlg;
 int nResponse = dlg.DoModal();
 if (nResponse == IDOK)
 {
  // TODO: Place code here to handle when the dialog is
  //  dismissed with OK
 }
 else if (nResponse == IDCANCEL)
 {
  // TODO: Place code here to handle when the dialog is
  //  dismissed with Cancel
 }

 // Since the dialog has been closed, return FALSE so that we exit the
 //  application, rather than start the application's message pump.
 return FALSE;
}

int CServerApp::ExitInstance()
{
 WSACleanup(); 
 return CWinApp::ExitInstance();
}
2、Server.h:

// Server.h : main header file for the SERVER application
//

#if !defined(AFX_SERVER_H__5CADC2CA_28BB_45BC_A086_32387F3D87BC__INCLUDED_)
#define AFX_SERVER_H__5CADC2CA_28BB_45BC_A086_32387F3D87BC__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#ifndef __AFXWIN_H__
 #error include 'stdafx.h' before including this file for PCH
#endif

#include "resource.h"  // main symbols

/
// CServerApp:
// See Server.cpp for the implementation of this class
//

class CServerApp : public CWinApp
{
public:
 CServerApp();

// Overrides
 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(CServerApp)
 public:
 virtual BOOL InitInstance();
 virtual int ExitInstance();
 //}}AFX_VIRTUAL

// Implementation

 //{{AFX_MSG(CServerApp)
  // NOTE - the ClassWizard will add and remove member functions here.
  //    DO NOT EDIT what you see in these blocks of generated code !
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};


/

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_SERVER_H__5CADC2CA_28BB_45BC_A086_32387F3D87BC__INCLUDED_)
3、ServerDlg.cpp:

// ServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Server.h"
#include "ServerDlg.h"

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

/
// CAboutDlg dialog used for App About

#define MYMESSAGE WM_USER+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()

/
// CServerDlg dialog

CServerDlg::CServerDlg(CWnd* pParent /*=NULL*/)
 : CDialog(CServerDlg::IDD, pParent)
{
 //{{AFX_DATA_INIT(CServerDlg)
 //m_IP = _T("");
 //strPort = _T("");
 //}}AFX_DATA_INIT
 // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CServerDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{{AFX_DATA_MAP(CServerDlg)
 DDX_Control(pDX, IDC_EDIT2, m_ServerPort);
 DDX_Control(pDX, IDC_EDIT1, m_ServerIP);
 //DDX_Text(pDX, IDC_EDIT1, m_IP);
// DDX_Text(pDX, IDC_EDIT2, strPort);
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CServerDlg, CDialog)
 //{{AFX_MSG_MAP(CServerDlg)
 ON_WM_SYSCOMMAND()
 ON_WM_PAINT()
 ON_WM_QUERYDRAGICON()
 ON_BN_CLICKED(IDC_BUTTON1, OnSetting)
 ON_MESSAGE(MYMESSAGE,TranslateData)
 ON_BN_CLICKED(IDC_BUTTON2, OnCancel)
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/
// CServerDlg message handlers

BOOL CServerDlg::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_SockServer=socket(AF_INET,SOCK_STREAM,0);
 WSAAsyncSelect(m_SockServer,m_hWnd,MYMESSAGE,FD_WRITE|FD_READ|FD_ACCEPT);
 m_ConnectNum=0;
 for(int i=0;i<MAXNUM;i++)
  m_Clients[i]=0;
 return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CServerDlg::TranslateData()
{
 sockaddr_in serveraddr;
 char buffer[1024];
 int len=sizeof(serveraddr);
 int curlink=-1;
 int num=-1;
 for(int i=0;i<MAXNUM;i++)
 {
  num=recv(m_Clients[i],buffer,1024,0);
  if(num!=-1)
  {
   curlink=i;
   break;
  }
 }
 buffer[num]=0;
 if(num==-1)
 {
  if(m_ConnectNum<MAXNUM)
  {
   m_Clients[m_ConnectNum]=accept(m_SockServer,(struct sockaddr*)&serveraddr,&len);
   m_ConnectNum++;
  }
  return;
 }
 for(int j=0;j<m_ConnectNum;j++)
  if(j!=curlink)
   send(m_Clients[j],buffer,num,0);
}

void CServerDlg::OnSetting()
{
 m_ServerIP.GetWindowText(m_IP); 
 CString strPort; 
    m_ServerPort.GetWindowText(strPort); 
 if (m_IP.IsEmpty() || strPort.IsEmpty()) 
    { 
        MessageBox("请设置服务器IP和端口号","提示"); 
        return; 
    } 
    m_Port = atoi(strPort); 
    sockaddr_in serveraddr; 
    serveraddr.sin_family = AF_INET; 
    serveraddr.sin_addr.S_un.S_addr  = inet_addr(m_IP); 
    serveraddr.sin_port = htons(m_Port); 
    if (bind(m_SockServer,(sockaddr*)&serveraddr,sizeof(serveraddr))) 
    { 
        MessageBox("绑定地址失败."); 
        return; 
    } 
 else
 {
  MessageBox("绑定地址成功。");
 }
 listen(m_SockServer,20); 
}

void CServerDlg::OnCancel()
{
 // TODO: Add your control notification handler code here
 OnOK();
}

BOOL CServerDlg::PreTranslateMessage(MSG* pMsg)
{
 // TODO: Add your specialized code here and/or call the base class
 if (pMsg->message==20000)

    {

        TranslateData();

        return TRUE;

    }

    else
  return CDialog::PreTranslateMessage(pMsg);
}
4、ServerDlg.h:

// ServerDlg.h : header file
//

#if !defined(AFX_SERVERDLG_H__1D1C1C43_AE8A_4FEC_BCF0_09F0BC473B38__INCLUDED_)
#define AFX_SERVERDLG_H__1D1C1C43_AE8A_4FEC_BCF0_09F0BC473B38__INCLUDED_
#include "winsock2.h"
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#pragma comment(lib,"ws2_32.lib")
#define MAXNUM 10 
/
// CServerDlg dialog
class CServerDlg : public CDialog
{
// Construction
public:
 void TranslateData();
 CServerDlg(CWnd* pParent = NULL);  
 SOCKET m_SockServer,m_SockClient; 
 SOCKET m_Clients[MAXNUM];    
 int m_ConnectNum; 
 CString m_IP;
 UINT m_Port; 


// Dialog Data
 //{{AFX_DATA(CServerDlg)
 enum { IDD = IDD_SERVER_DIALOG };
 CEdit m_ServerPort;
 CEdit m_ServerIP;
 //CString m_IP;
 CString strPort;
 //}}AFX_DATA

 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(CServerDlg)
 public:
 virtual BOOL PreTranslateMessage(MSG* pMsg);
 protected:
 virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
 //}}AFX_VIRTUAL

// Implementation
protected:
 HICON m_hIcon;

 // Generated message map functions
 //{{AFX_MSG(CServerDlg)
 virtual BOOL OnInitDialog();
 afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
 afx_msg void OnPaint();
 afx_msg HCURSOR OnQueryDragIcon();
 afx_msg void OnSetting();
 afx_msg void OnCancel();
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_SERVERDLG_H__1D1C1C43_AE8A_4FEC_BCF0_09F0BC473B38__INCLUDED_)
5、Resource.h:

//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by Server.rc
//
#define IDM_ABOUTBOX                    0x0010
#define IDD_ABOUTBOX                    100
#define IDS_ABOUTBOX                    101
#define IDD_SERVER_DIALOG               102
#define IDR_MAINFRAME                   128
#define IDC_EDIT1                       1000
#define IDC_EDIT2                       1001
#define IDC_BUTTON1                     1002
#define IDC_BUTTON2                     1003

// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE        129
#define _APS_NEXT_COMMAND_VALUE         32771
#define _APS_NEXT_CONTROL_VALUE         1003
#define _APS_NEXT_SYMED_VALUE           101
#endif
#endif
6、stdafx.h:

// stdafx.h : include file for standard system include files,
//  or project specific include files that are used frequently, but
//      are changed infrequently
//

#if !defined(AFX_STDAFX_H__F5162983_68DA_4D6B_B1CD_1F46DE972FBA__INCLUDED_)
#define AFX_STDAFX_H__F5162983_68DA_4D6B_B1CD_1F46DE972FBA__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define VC_EXTRALEAN  // Exclude rarely-used stuff from Windows headers

#include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions
#include <afxdisp.h>        // MFC Automation classes
#include <afxdtctl.h>  // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>   // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT


//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_STDAFX_H__F5162983_68DA_4D6B_B1CD_1F46DE972FBA__INCLUDED_)
7、stdafx.cpp:

// stdafx.cpp : source file that includes just the standard includes
// Server.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

三、运行测试:

运行成功!回去吃饭!


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
================================================== 系统名称:C2C在线聊天系统插件(asp版) 当前版本:FeiHu_Chat Version 1.1 官方网站:飞虎网络(www.asp188.cn) QQ:290052621 作 者: 飞虎 ================================================== Copyright 2008 asp188.cn - All Rights Reserved. ================================================== [已通过安全检测]卡巴斯基7.0 [病毒文件版本号] 2008-6-4 [已通过安装测试]Windows XP SP3 + IIS6.0 *-------------* 绝对不含脚本! *-------------* 北京飞虎工作室: http://www.asp188.cn 感谢支持!您的支持是我最大的动力! ---------------------------------------------------------------- “C2C在线聊天系统”程序说明: ━┅━┅━┅━┅━┅━┅━┅━┅━━┅━┅━┅━┅━┅━┅━┅━ 1) 将之解压到你的网站目录,所有文件都放在一个文件夹中即可使用,主文件“chat_index.asp” 2) 可以点对点聊天,实现在线互动,而不用安装任何插件,是虚拟空间网站的“福星” 3) 本程序采用session传递用户名参数,用户可以很容易和自己的系统整合 4) 本程序没有做SQL防注入,因为每个网站都会有这一项(我就偷懒了) 所以用户网站只要包含自己的<!--#include file="conn.asp"-->就OK了 5) 用户可以将数据库整合到自己的数据库中,不过鄙人不建议这么做(原因请看6) 6) 新进用户会自动建立一个表,离开时再删除,如果你的站人数比较多,那么会影响主数据库的访问 所以,把聊天数据库独立放置比较好 7) 本系统对话框采用MSN的风格界面,美观大方 8) 系统用到三个session,session("fh_name_from")、session("fh_name_to")、session("fh_name_db") 分别是:自己的昵称、对方昵称、所在的数据库名,三个参数要与自己的系统进行整合 9) 免责声明:本程序系共享软件,如因本程序漏洞而给贵站带来损失的,原作者不负任何责任 请记住我的域名:http://www.asp188.cn 记住我的QQ号码:290052621
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值