经过一天的折腾,总算把自己的第一个简单的聊天系统给弄出来了,基于C/S架构的,主要用了windows提供的API。(红色的代码是自己写的).
此外值得一提的是在服务器端及客户端我都创建了一个线程来接收对方发来的信息。线程入口函数UINT thread(LPVOID p)在类外定义。
服务器端部分代码:
// SvrDlg.cpp : implementation file
//
#include "stdafx.h"
#include "Svr.h"
#include "SvrDlg.h"
#include "Winsock2.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// CAboutDlg dialog used for App About
SOCKET sockSrv;
SOCKET sockConn;
char recvBuf[100];
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()
/
// CSvrDlg dialog
CSvrDlg::CSvrDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSvrDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CSvrDlg)
m_strSvr = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CSvrDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSvrDlg)
DDX_Control(pDX, IDC_LIST1, m_Slist);
DDX_Control(pDX, IDC_EDIT1, m_Svr);
DDX_Text(pDX, IDC_EDIT1, m_strSvr);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CSvrDlg, CDialog)
//{{AFX_MSG_MAP(CSvrDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDOPEN, OnOpen)
ON_BN_CLICKED(IDCLOSE, OnClose)
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/
// CSvrDlg message handlers
BOOL CSvrDlg::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
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return FALSE;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return FALSE;
}
m_Slist.InsertColumn(0,"消息");
m_Slist.SetColumnWidth(0,400);
count = 0;
return TRUE; // return TRUE unless you set the focus to a control
}
void CSvrDlg::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 CSvrDlg::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 CSvrDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CSvrDlg::OnOpen()
{
// TODO: Add your control notification handler code here
sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
if(listen(sockSrv,5)==0)
{
MessageBox("开始监听来自客户端的请求");
}
AfxBeginThread(&thread,0);
}
void CSvrDlg::OnClose()
{
// TODO: Add your control notification handler code here
WSACleanup( );
closesocket(sockConn);
CDialog::OnCancel();
}
void CSvrDlg::OnButton1()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
send(sockConn, m_strSvr,sizeof( m_strSvr)+1,0);
m_Slist.InsertItem(count++,"我说:");
m_Slist.InsertItem(count++,m_strSvr);
m_Svr.SetWindowText("");
}
UINT thread(LPVOID p)
{
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
CSvrDlg *dlg=(CSvrDlg*)AfxGetApp()->GetMainWnd();
int s = 1;
sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
if(sockConn)
{
MessageBox(NULL,"连接客户端成功","OKOK",MB_OK);
}
while(s!=SOCKET_ERROR)
{
s=recv(sockConn,recvBuf,100,0);
if(s!=SOCKET_ERROR)
{
// dlg->m_Svr.SetWindowText(recvBuf);
dlg->m_Slist.InsertItem(dlg->count++,"对方说:");
dlg->m_Slist.InsertItem(dlg->count++,recvBuf);
}
}
AfxEndThread(0);
return 0;
}
客户端的部分代码:
// ClientDlg.cpp : implementation file
//
#include "stdafx.h"
#include "Client.h"
#include "ClientDlg.h"
#include "Winsock2.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// CAboutDlg dialog used for App About
SOCKET sockClient;
char recvBuf[100];
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)
m_strClient = _T("");
//}}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_LIST1, m_Clist);
DDX_Control(pDX, IDC_CLIENT, m_Client);
DDX_Text(pDX, IDC_CLIENT, m_strClient);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CClientDlg, CDialog)
//{{AFX_MSG_MAP(CClientDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDLINK, OnLink)
ON_BN_CLICKED(IDC_SEND, 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
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return FALSE;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return FALSE;
}
m_Clist.InsertColumn(0,"消息");
m_Clist.SetColumnWidth(0,400);
count = 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::OnLink()
{
// TODO: Add your control notification handler code here
sockClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
if(!connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)))
{
MessageBox("连接服务器成功!!!!!");
}
AfxBeginThread(&clientthread,0);
}
void CClientDlg::OnSend()
{
// TODO: Add your control notification handler code here
CSize size;
size.cx=0;
size.cy=30;
UpdateData(TRUE);
send(sockClient,m_strClient,strlen(m_strClient)+1,0);
m_Client.SetWindowText("");
m_Clist.InsertItem(count++,"我说:");
m_Clist.InsertItem(count++, m_strClient);
m_Clist.Scroll(size);
}
UINT clientthread(LPVOID p)
{
int s =1;
CClientDlg *dlg=(CClientDlg*)AfxGetApp()->GetMainWnd();
while(s!=SOCKET_ERROR)
{
s=recv(sockClient,recvBuf,100,0);
if(s!=SOCKET_ERROR)
{
dlg->m_Clist.InsertItem(dlg->count++,"对方说:");
dlg->m_Clist.InsertItem(dlg->count++,recvBuf);
}
}
AfxEndThread(0);
return 0;
}
void CClientDlg::OnCancel()
{
// TODO: Add extra cleanup here
WSACleanup();
closesocket(sockClient);
CDialog::OnCancel();
}
这个只是个非常简单的框架而已,接下来的工作就是在上面继续完善功能了,希望做成点对点的,顺便还可以做个文件传输功能以及最好能够保存通话记录。