| 网站首页 | JAVA文章 | AppServers | Web开发 | 应用开发 | 资源下载 | 论坛
    想学好编程,学好外语很重要  [enadd  2006年12月25日]        
设为首页 加入收藏 联系站长
您现在的位置: 编程笔记网 >> 应用开发 >> vc >> 通信网络 >> 文章正文
WinSocket高级实现(聊天室的实现)(一)        【字体:
WinSocket高级实现(聊天室的实现)(一)
作者:-    文章来源:-    点击数:    更新时间:2006-4-20

  上次的文章我给大家简单的介绍了一下WinSocket的使用方法,相信大家已经对它产生了一定的兴趣,接下来我会带领大家进入网络编程的世界,今天我会逐步的给大家讲解如何利用WinSocket实现一个网络聊天室。正如大多数聊天室一样,我们需要一个聊天服务器它可以和很多客户端进行通信,从而实现把来自不同的客户的聊天信息转交到所有其他的客户端。这样就形成一个采用C/S结构的可以多人同时在线的聊天室。今天我们就利用上次文章中的知识来实现它。(这里我们需要你有一些VC的MFC知识,最好可以会编一些简单的窗口程序,当然我也会尽可能的讲的具体一些。)

我们先来做一个客户端。

首先启动VC,利用MFC AppWizard[EXE]建立一个新的MFC程序,取名为ChatRoom,在MFC AppWizard Step 1的时候我们选择Dialog based,在Step 2时我们一定要选择上Windows Sockets选项,切记!切记!之后的几步我们就可以使用默认值了。

我们要做的客户端分为两个窗口,一个是登陆窗口,需要你输入一些登陆信息,另外就是聊天主窗口。如下图:

相信这两个窗口不难建立吧?其中那个聊天主窗口是程序生成的时候自己建立的,而那个登陆窗口是后添进去的,为了可以在主窗口出现之前启动先启动登陆窗口,我们需要在CChatRoomApp::InitInstance中更改代码。(其中我们为登陆窗口建立的类叫ConnectDlg)

BOOL CChatRoomApp::InitInstance()
{
  if (!AfxSocketInit())
  {
    AfxMessageBox(IDP_SOCKETS_IN99v_FAILED);
    return FALSE;
  }

  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
  CClientSocket *tmpSocket;
  CConnectDlg *cdlg;
  CChatRoomDlg *dlg;
  int nResponse,cnResponse=IDOK,endFlage=1;
  tmpSocket=new CClientSocket;
  cdlg=new CConnectDlg(tmpSocket);
  cnResponse=cdlg->DoModal();
  if (cnResponse == IDCANCEL)
  {
    // TODO: Place code here to handle when the dialog is
    // dismissed with Cancel
    delete tmpSocket;
    delete cdlg;
    return FALSE;
  }
  else
  {
    delete cdlg;
  }
  dlg=new CChatRoomDlg(tmpSocket);
  tmpSocket->SetDlg(dlg);
  nResponse = dlg->DoModal();
  m_pMainWnd = dlg;
  if (nResponse == IDOK)
  {
    // TODO: Place code here to handle when the dialog is
    // dismissed with OK
    if (tmpSocket) tmpSocket->Close();
    tmpSocket->myDlg=NULL;
    delete tmpSocket;
    tmpSocket=NULL;
  }
  else if (nResponse == IDCANCEL)
  {
    // TODO: Place code here to handle when the dialog is
    // dismissed with Cancel
    if (tmpSocket) tmpSocket->Close();
    delete tmpSocket;
  }
  // Since the dialog has been closed, return FALSE so that we exit the
  // application, rather than start the application's message pump.
  return FALSE;
 }

[1] [2] [3] 下一页  

文章录入:enadd    责任编辑:enadd 
  • 上一篇文章:

  • 下一篇文章: 没有了
  • 发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
    最新热点 最新推荐 相关文章
  • 一个对Winsock 完成端口模型…

  • 一个Socket传输文件的例子

  • 用VC++6.0的Sockets API实现…

  • 在VC中实现FTP功能

  • 直接用socket实现HTTP下载

  • WinSocket高级实现(聊天室的…

  • ftp协议实现多线程断点续传

  • 应用层截包方案与实现

  • udp服务器设计过程总结

  • 局域网内mfc/udp聊天程序

  •   网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)
    | 设为首页 | 加入收藏 | 联系站长 | 友情链接 | 版权申明 | 管理登录 |