基于CS简单聊天程序课程设计
cs聊天软件课程设计

cs聊天软件课程设计一、课程目标知识目标:1. 学生能理解聊天软件的基本原理和功能,掌握CS架构的网络通信技术。
2. 学生能了解并描述聊天软件中的数据传输方式,如TCP/IP协议。
3. 学生掌握基本的编程知识,能利用编程语言实现简单的聊天软件功能。
技能目标:1. 学生能运用所学知识,设计并实现一个简单的聊天软件界面。
2. 学生能通过编程实现聊天软件的发送、接收消息功能,并掌握异步处理技术。
3. 学生具备问题解决能力,能针对聊天软件在实际应用中遇到的问题进行分析和调试。
情感态度价值观目标:1. 培养学生对网络通信技术的兴趣,激发他们探索网络编程领域的热情。
2. 培养学生的团队协作精神,使他们能在项目实践中互相帮助,共同解决问题。
3. 培养学生具有良好的网络素养,明白网络通信中的安全与道德规范,树立正确的网络安全观念。
课程性质:本课程为实践性较强的课程,结合课本知识,让学生在动手实践中掌握聊天软件的开发技能。
学生特点:学生具备一定的编程基础,对网络通信技术有一定了解,但对实际应用开发相对陌生。
教学要求:注重理论与实践相结合,以学生为主体,鼓励他们积极参与实践,培养解决问题的能力。
同时,关注学生的情感态度价值观培养,提升他们的综合素质。
通过本课程的学习,使学生能够达到上述课程目标,并具备进一步探索网络编程领域的能力。
二、教学内容1. 聊天软件概述:介绍聊天软件的发展历程、分类及其在生活中的应用。
- 相关章节:教材第3章“网络应用软件”2. 网络通信基础:讲解CS架构、TCP/IP协议、端口号等基础知识。
- 相关章节:教材第2章“网络通信基础”3. 聊天软件功能模块设计:分析聊天软件的主要功能模块,如用户注册、登录、添加好友、发送接收消息等。
- 相关章节:教材第4章“软件工程”4. 编程语言选择与开发环境配置:选择合适的编程语言(如Python、Java 等),介绍开发环境的配置方法。
- 相关章节:教材第1章“编程语言概述”及第6章“开发环境配置”5. 实现简单的聊天软件功能:根据功能模块设计,指导学生利用编程语言实现以下功能:- 用户注册与登录- 添加好友与创建群聊- 发送、接收消息(文字、图片等)- 消息推送与实时通信- 相关章节:教材第5章“网络编程”6. 项目实践:安排学生分组进行项目实践,完成一个具有基本功能的聊天软件。
网络程序设计课程设计--VC(MFC)实现简单的聊天室程序

《网络程序设计》课程设计报告书题目:简单的聊天室程序专业:网络工程完成日期:一、题目:简单的聊天室程序要求:本题是一个简单的聊天室程序,采用客户/服务器模式,分为客户端程序和服务器端程序。
由于服务器只能支持一个客户,实际上是一个点对点通信的程序。
客户端程序和服务器程序通过网络交换聊天字符串内容,并在窗口的列表框中显示。
二、系统概要设计聊天室是分客户端和服务端两个应用程序的,两个应用程序要想实现交互必须编写相应的指令和识别指令的代码,我写的这是个指令依次是启动停止用户退出的命令,但用户想要进行以上动作中的任何一个时,在用户按下按键的时候,客户端都是向服务端发送相应的指令,再由服务端实际的执行。
三、系统详细设计对概要设计中提到的功能函数进行详细设计。
服务器端:// ChatRoomServerDlg.cpp : implementation file//#include "stdafx.h"#include "ChatRoomServer.h"#include "ChatRoomServerDlg.h"#include "ListenSocket.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CAboutDlg dialog used for App Aboutclass 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// Implementationprotected://{{AFX_MSG(CAboutDlg)//}}AFX_MSGDECLARE_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_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CChatRoomServerDlg dialogCChatRoomServerDlg::CChatRoomServerDlg(CWnd* pParent /*=NULL*/) : CDialog(CChatRoomServerDlg::IDD, pParent){//{{AFX_DATA_INIT(CChatRoomServerDlg)// 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 CChatRoomServerDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CChatRoomServerDlg)DDX_Control(pDX, IDC_BUTTON_STOP, m_IDC_BUTTON_STOP);DDX_Control(pDX, IDC_BUTTON_START, m_IDC_BUTTON_START);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CChatRoomServerDlg, CDialog)//{{AFX_MSG_MAP(CChatRoomServerDlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_BUTTON_START, OnButtonStart)ON_BN_CLICKED(IDC_BUTTON_STOP, OnButtonStop)//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CChatRoomServerDlg message handlersBOOL CChatRoomServerDlg::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 dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization herem_IDC_BUTTON_STOP.EnableWindow(FALSE);return TRUE; // return TRUE unless you set the focus to a control}void CChatRoomServerDlg::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 CChatRoomServerDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint 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 icondc.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 CChatRoomServerDlg::OnQueryDragIcon()return (HCURSOR) m_hIcon;}void CChatRoomServerDlg::OnButtonStart(){// TODO: Add your control notification handler code herem_IDC_BUTTON_START.EnableWindow(FALSE);//使启动按钮无效ListenSocket.Create(6767);//创建监听套接字端口为6767ListenSocket.Listen();//开始监听m_IDC_BUTTON_STOP.EnableWindow(TRUE);//将停止按钮激活}void CChatRoomServerDlg::OnButtonStop(){// TODO: Add your control notification handler code herem_IDC_BUTTON_STOP.EnableWindow(FALSE);//使停止按钮无效ListenSocket.Close();//关闭监听套接字m_IDC_BUTTON_START.EnableWindow(TRUE);//将启动按钮激活}// ChatRoomServer.h : main header file for the CHATROOMSERVER application//#if !defined(AFX_CHA TROOMSERVER_H__680EC642_E19B_4D55_88DF_2C9E9B1B30FD __INCLUDED_)#defineAFX_CHATROOMSERVER_H__680EC642_E19B_4D55_88DF_2C9E9B1B30FD__INCLUDE D_#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/////////////////////////////////////////////////////////////////////////////// CChatRoomServerApp:// See ChatRoomServer.cpp for the implementation of this class//class CChatRoomServerApp : public CWinApp{public:CChatRoomServerApp();// Overrides// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CChatRoomServerApp)public:virtual BOOL InitInstance();//}}AFX_VIRTUAL// Implementation//{{AFX_MSG(CChatRoomServerApp)// NOTE - the ClassWizard will add and remove member functions here.// DO NOT EDIT what you see in these blocks of generated code !//}}AFX_MSGDECLARE_MESSAGE_MAP()};///////////////////////////////////////////////////////////////////////////////{{AFX_INSERT_LOCA TION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif// !defined(AFX_CHATROOMSERVER_H__680EC642_E19B_4D55_88DF_2C9E9B1B30FD__ INCLUDED_)// ChatRoomServerDlg.h : header file//#if !defined(AFX_CHA TROOMSERVERDLG_H__5BE648B6_8A9C_4E90_BF1D_20FE943A5 25F__INCLUDED_)#defineAFX_CHATROOMSERVERDLG_H__5BE648B6_8A9C_4E90_BF1D_20FE943A525F__INCL UDED_#include "ClientSocketList.h" // Added by ClassView#include "ListenSocket.h" // Added by ClassView#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000/////////////////////////////////////////////////////////////////////////////// CChatRoomServerDlg dialogclass CChatRoomServerDlg : public CDialog{// Constructionpublic:CListenSocket ListenSocket;CChatRoomServerDlg(CWnd* pParent = NULL); // standard constructor// Dialog Data//{{AFX_DATA(CChatRoomServerDlg)enum { IDD = IDD_CHATROOMSERVER_DIALOG };CButton m_IDC_BUTTON_STOP;CButton m_IDC_BUTTON_START;//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CChatRoomServerDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support//}}AFX_VIRTUAL// Implementationprotected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CChatRoomServerDlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnButtonStart();afx_msg void OnButtonStop();//}}AFX_MSGDECLARE_MESSAGE_MAP()};//{{AFX_INSERT_LOCA TION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif// !defined(AFX_CHA TROOMSERVERDLG_H__5BE648B6_8A9C_4E90_BF1D_20FE943A52 5F__INCLUDED_)#if !defined(AFX_CLIENTSOCKET_H__5B707F31_3AD5_4F47_B58E_ECFC99EB60F0__IN CLUDED_)#defineAFX_CLIENTSOCKET_H__5B707F31_3AD5_4F47_B58E_ECFC99EB60F0__INCLUDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000// ClientSocket.h : header file///////////////////////////////////////////////////////////////////////////////// CClientSocket command targetclass CClientSocketList;class CClientSocket : public CSocket{// Attributespublic:// Operationspublic:CClientSocket(CClientSocketList *);virtual ~CClientSocket();// Overridespublic:CClientSocketList *List;CClientSocket * Front;CClientSocket * Next;// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CClientSocket)public:virtual void OnReceive(int nErrorCode);virtual void OnClose(int nErrorCode);//}}AFX_VIRTUAL// Generated message map functions//{{AFX_MSG(CClientSocket)// NOTE - the ClassWizard will add and remove member functions here.//}}AFX_MSG// Implementationprotected:};///////////////////////////////////////////////////////////////////////////////{{AFX_INSERT_LOCA TION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif// !defined(AFX_CLIENTSOCKET_H__5B707F31_3AD5_4F47_B58E_ECFC99EB60F0__INC LUDED_)// ClientSocketList.h: interface for the CClientSocketList class.////////////////////////////////////////////////////////////////////////#if !defined(AFX_CLIENTSOCKETLIST_H__E746355D_FA10_4D12_B544_2FF152C16414__ INCLUDED_)#defineAFX_CLIENTSOCKETLIST_H__E746355D_FA10_4D12_B544_2FF152C16414__INCLUDE D_#include "ClientSocket.h"#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000class CClientSocketList{public:BOOL Sends(CClientSocket *);BOOL Add(CClientSocket *);CClientSocket * Head;CClientSocketList();virtual ~CClientSocketList();};#endif// !defined(AFX_CLIENTSOCKETLIST_H__E746355D_FA10_4D12_B544_2FF152C16414__I NCLUDED_)#if !defined(AFX_LISTENSOCKET_H__5D655304_370E_4680_A556_E417552D24EC__INC LUDED_)#defineAFX_LISTENSOCKET_H__5D655304_370E_4680_A556_E417552D24EC__INCLUDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000// ListenSocket.h : header file//#include "ClientSocketList.h"/////////////////////////////////////////////////////////////////////////////// CListenSocket command targetclass CListenSocket : public CSocket{// Attributespublic:// Operationspublic:CClientSocketList CCSL;//客户socket列表CListenSocket();virtual ~CListenSocket();// Overridespublic:// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CListenSocket)public:virtual void OnAccept(int nErrorCode); //重载OnAccept函数//}}AFX_VIRTUAL// Generated message map functions//{{AFX_MSG(CListenSocket)// NOTE - the ClassWizard will add and remove member functions here.//}}AFX_MSG// Implementationprotected:};///////////////////////////////////////////////////////////////////////////////{{AFX_INSERT_LOCA TION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif// !defined(AFX_LISTENSOCKET_H__5D655304_370E_4680_A556_E417552D24EC__INCL UDED_)// ChatRoomServer.cpp : Defines the class behaviors for the application.//#include "stdafx.h"#include "ChatRoomServer.h"#include "ChatRoomServerDlg.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CChatRoomServerAppBEGIN_MESSAGE_MAP(CChatRoomServerApp, CWinApp)//{{AFX_MSG_MAP(CChatRoomServerApp)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSGON_COMMAND(ID_HELP, CWinApp::OnHelp)END_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CChatRoomServerApp constructionCChatRoomServerApp::CChatRoomServerApp(){// TODO: add construction code here,// Place all significant initialization in InitInstance}/////////////////////////////////////////////////////////////////////////////// The one and only CChatRoomServerApp objectCChatRoomServerApp theApp;/////////////////////////////////////////////////////////////////////////////// CChatRoomServerApp initializationBOOL CChatRoomServerApp::InitInstance(){if (!AfxSocketInit()){AfxMessageBox(IDP_SOCKETS_INIT_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 _AFXDLLEnable3dControls(); // Call this when using MFC in a shared DLL #elseEnable3dControlsStatic(); // Call this when linking to MFC statically#endifCChatRoomServerDlg 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;}II 客户端:客户端:// ChatRoomClient.cpp : Defines the class behaviors for the application.//#include "stdafx.h"#include "ChatRoomClient.h"#include "ChatRoomClientDlg.h"#include "ConnectedDlg.h"#include "ClientSocket.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifCClientSocket curSocket;/////////////////////////////////////////////////////////////////////////////// CChatRoomClientAppBEGIN_MESSAGE_MAP(CChatRoomClientApp, CWinApp)//{{AFX_MSG_MAP(CChatRoomClientApp)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSGON_COMMAND(ID_HELP, CWinApp::OnHelp)END_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CChatRoomClientApp constructionCChatRoomClientApp::CChatRoomClientApp(){// TODO: add construction code here,// Place all significant initialization in InitInstance}/////////////////////////////////////////////////////////////////////////////// The one and only CChatRoomClientApp objectCChatRoomClientApp theApp;/////////////////////////////////////////////////////////////////////////////// CChatRoomClientApp initializationBOOL CChatRoomClientApp::InitInstance(){if (!AfxSocketInit()){AfxMessageBox(IDP_SOCKETS_INIT_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 _AFXDLLEnable3dControls(); // Call this when using MFC in a shared DLL #elseEnable3dControlsStatic(); // Call this when linking to MFC statically#endifCConnectedDlg cdlg(&curSocket);if (cdlg.DoModal()==IDCANCEL) return FALSE;CChatRoomClientDlg dlg(&curSocket);m_pMainWnd = &dlg;curSocket.SetDlg(&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;}// ChatRoomClientDlg.cpp : implementation file//#include "stdafx.h"#include "ChatRoomClient.h"#include "ChatRoomClientDlg.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CAboutDlg dialog used for App Aboutclass 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// Implementationprotected://{{AFX_MSG(CAboutDlg)//}}AFX_MSGDECLARE_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_MAPBEGIN_MESSAGE_MAP(CAboutDlg, CDialog)//{{AFX_MSG_MAP(CAboutDlg)// No message handlers//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CChatRoomClientDlg dialogCChatRoomClientDlg::CChatRoomClientDlg(CClientSocket *tmp,CWnd* pParent /*=NULL*/) : CDialog(CChatRoomClientDlg::IDD, pParent){//{{AFX_DATA_INIT(CChatRoomClientDlg)m_IDC_EDIT_MESSAGE = _T("");//}}AFX_DATA_INIT// Note that LoadIcon does not require a subsequent DestroyIcon in Win32m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);myServerSocket=tmp;}void CChatRoomClientDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CChatRoomClientDlg)DDX_Control(pDX, IDC_STATIC_NIKENAME, m_STATIC_NIKENAME_CONTROL);DDX_Control(pDX, IDC_LIST_CHA TBOX, m_IDC_LIST_CHATBOX_CONTROL);DDX_Text(pDX, IDC_EDIT_MESSAGE, m_IDC_EDIT_MESSAGE);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CChatRoomClientDlg, CDialog)//{{AFX_MSG_MAP(CChatRoomClientDlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_BUTTON_SEND, OnButtonSend)//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CChatRoomClientDlg message handlersBOOL CChatRoomClientDlg::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 dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small iconm_STATIC_NIKENAME_CONTROL.SetWindowText(myServerSocket->NikeName);// TODO: Add extra initialization herereturn TRUE; // return TRUE unless you set the focus to a control}void CChatRoomClientDlg::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 CChatRoomClientDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint 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 icondc.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 CChatRoomClientDlg::OnQueryDragIcon(){return (HCURSOR) m_hIcon;}BOOL CChatRoomClientDlg::GetMessage(){char buff[1000];int count;count=myServerSocket->Receive(buff,1000);buff[count]=0;m_IDC_LIST_CHA TBOX_CONTROL.AddString(buff);return true;void CChatRoomClientDlg::OnButtonSend(){// TODO: Add your control notification handler code hereint n;char message[1000];UpdateData(TRUE);m_IDC_EDIT_MESSAGE=myServerSocket->NikeName+": "+m_IDC_EDIT_MESSAGE;n=m_IDC_EDIT_MESSAGE.GetLength();//message=new char(n+1);sprintf(message,"%s",m_IDC_EDIT_MESSAGE.GetBuffer(n));message[n]=0;if (myServerSocket->Send(message,n+1)){m_IDC_EDIT_MESSAGE="";UpdateData(FALSE);}else{AfxMessageBox("网络传输错误!!!");}}// ClientSocket.cpp : implementation file//#include "stdafx.h"#include "ChatRoomClient.h"#include "ClientSocket.h"#include "ChatRoomClientDlg.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CClientSocketCClientSocket::CClientSocket()NikeName="";myDlg=0;}CClientSocket::~CClientSocket(){}BOOL CClientSocket::SetDlg(CChatRoomClientDlg *tmp){myDlg=tmp;return true;}// Do not edit the following lines, which are needed by ClassWizard.#if 0BEGIN_MESSAGE_MAP(CClientSocket, CSocket)//{{AFX_MSG_MAP(CClientSocket)//}}AFX_MSG_MAPEND_MESSAGE_MAP()#endif // 0/////////////////////////////////////////////////////////////////////////////// CClientSocket member functionsvoid CClientSocket::OnReceive(int nErrorCode){// TODO: Add your specialized code here and/or call the base class myDlg->GetMessage();CSocket::OnReceive(nErrorCode);}// ConnectedDlg1.cpp : implementation file//#include "stdafx.h"#include "ChatRoomClient.h"#include "ConnectedDlg.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CConnectedDlg dialogCConnectedDlg::CConnectedDlg(CClientSocket * tmp,CWnd* pParent /*=NULL*/) : CDialog(CConnectedDlg::IDD, pParent){//{{AFX_DATA_INIT(CConnectedDlg)m_IDC_EDIT_ADDRESS = _T("");m_IDC_EDIT_NIKENAME = _T("");//}}AFX_DATA_INITmyServerSocket=tmp;}void CConnectedDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CConnectedDlg)DDX_Text(pDX, IDC_EDIT_ADDRESS, m_IDC_EDIT_ADDRESS);DDX_Text(pDX, IDC_EDIT_NIKENAME, m_IDC_EDIT_NIKENAME);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CConnectedDlg, CDialog)//{{AFX_MSG_MAP(CConnectedDlg)//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CConnectedDlg message handlersvoid CConnectedDlg::OnOK(){// TODO: Add extra validation hereUpdateData(TRUE);char *nikename,*address;int n;if (!myServerSocket->Create()){myServerSocket->Close();AfxMessageBox("网络创建错误!!");return;}n=m_IDC_EDIT_ADDRESS.GetLength();address=new char(n+1);sprintf(address,"%s",m_IDC_EDIT_ADDRESS.GetBuffer(n));address[n]=0;n=m_IDC_EDIT_NIKENAME.GetLength();nikename=new char(n+1);sprintf(nikename,"%s",m_IDC_EDIT_NIKENAME.GetBuffer(n));nikename[n]=0;if (!myServerSocket->Connect(address,6767)){myServerSocket->Close();AfxMessageBox("网络连接错误!请重新检查服务器地址的填写是否正确?");return;}myServerSocket->NikeName=nikename;CDialog::OnOK();}// stdafx.cpp : source file that includes just the standard includes// ChatRoomClient.pch will be the pre-compiled header// stdafx.obj will contain the pre-compiled type information#include "stdafx.h"// ChatRoomClient.h : main header file for the CHATROOMCLIENT application//#if !defined(AFX_CHATROOMCLIENT_H__4503F0DD_CA95_4F24_B6EE_3183B64B095B_ _INCLUDED_)#defineAFX_CHATROOMCLIENT_H__4503F0DD_CA95_4F24_B6EE_3183B64B095B__INCLUDE D_#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/////////////////////////////////////////////////////////////////////////////// CChatRoomClientApp:// See ChatRoomClient.cpp for the implementation of this class//class CChatRoomClientApp : public CWinApp{public:CChatRoomClientApp();// Overrides// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CChatRoomClientApp)public:virtual BOOL InitInstance();//}}AFX_VIRTUAL// Implementation//{{AFX_MSG(CChatRoomClientApp)// NOTE - the ClassWizard will add and remove member functions here.// DO NOT EDIT what you see in these blocks of generated code !//}}AFX_MSGDECLARE_MESSAGE_MAP()};///////////////////////////////////////////////////////////////////////////////{{AFX_INSERT_LOCA TION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif// !defined(AFX_CHATROOMCLIENT_H__4503F0DD_CA95_4F24_B6EE_3183B64B095B__I NCLUDED_)// ChatRoomClientDlg.h : header file//#if !defined(AFX_CHATROOMCLIENTDLG_H__4DF07865_B696_4641_82F8_4B32BF39595 9__INCLUDED_)#defineAFX_CHATROOMCLIENTDLG_H__4DF07865_B696_4641_82F8_4B32BF395959__INCLU DED_#include "ClientSocket.h" // Added by ClassView#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000//class ClientSocket;/////////////////////////////////////////////////////////////////////////////// CChatRoomClientDlg dialogclass CChatRoomClientDlg : public CDialog{// Constructionpublic:CClientSocket * myServerSocket;BOOL GetMessage();CChatRoomClientDlg(CClientSocket *,CWnd* pParent = NULL); // standard constructor// Dialog Data//{{AFX_DATA(CChatRoomClientDlg)enum { IDD = IDD_CHATROOMCLIENT_DIALOG };CStatic m_STATIC_NIKENAME_CONTROL;CListBox m_IDC_LIST_CHA TBOX_CONTROL;CString m_IDC_EDIT_MESSAGE;//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CChatRoomClientDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support//}}AFX_VIRTUAL// Implementationprotected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CChatRoomClientDlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnButtonSend();//}}AFX_MSGDECLARE_MESSAGE_MAP()};//{{AFX_INSERT_LOCA TION}}。
基于CS结构的聊天室系统方案

基于C\S结构的聊天室系统摘要计算机网络的迅速发展,对人类社会诸多领域产生了巨大的影响。
尤其是,随着信息时代的来临,人们之间愈来愈趋向于通过网络来交流和传递信息。
而聊天系统正是当前人们使用最多的中介。
在这个平台上,许多认识或不认识的人们彼此间能够随意的相互交交流。
因此,开发和架构这种平台符合时代发展的需要。
论文首先对目前国国际方面的状况进行初步的介绍,接下来详细的介绍了本设计用到的主要技术及相关容,以下按照软件工程的思想对系统进行调研,技术可行性分析,需求分析及总体设计与功能模块划分。
接着是详细设计按照不同的模块有侧重的分析,诸如客户端与服务器的通讯,客户端与客户端的通讯,涉及到本设计主要的流程,用流程图加以说明,并有文字说明。
本设计主要采用了黑盒测试与其他设计相结合的方法。
主要测试系统是否能完成基本的功能,当输入错误的信息时,提示信息是否合理;发送信息、接收信息是否按预想的设计进行;界面的合理、整洁性。
黑盒测试是从用户的角度出发的一种比较好的测试方法。
本设计分为四章,第一、二章是绪论与文献综述,介绍了本课题的来源背景、研究和解决的问题以及对社会发展的作用。
第三、四章提出了解决问题的方案以及提出具体的方法实现该系统的功能,这两章是最重要的部分。
第五章是本设计的结果与评价,对此系统在整体上进行测试,并做出客观的评价。
最后是致和参考文献,对此设计有帮助的人表示感以及自己所参考的重要文献。
关键词聊天系统;TCP/IP协议;JSPAbstractThe rapid development of the computer networks has been making a great influence in many fields of human society. In particular, along with information age approaching, people tend to increasingly communicate and transmit information through the network. But the chat system is precisely used by people as an intermediary. On this platform, people can chat each other at random whether they know or not. Therefore, this kind of platform developed and constructed conforms to demanding of the time.First the papers introduce the current domestic and international situation. Next, the main technology and the connected content are introduced in detail. Following is the investigation and study according to the software engineering thought to the system, the demand analysis and the system design and the function module. Next is the design which is according to the different module the analysis, such as client and server communications, client and the client communications. In this part also has the design of the main flow, and flow charts to illustrate and text description .The main design mainly uses the Black-box design and the combination of different methods.The fifth chapter is this design result and the appraisal, regarding this systematically carries on the test in the whole, and makes the objective appraisal,studying and solving problem and the function of the social development. Finally is the acknowledgment and the reference, regarding this designs has the help person to express thanks as well as own refer important literature.Keywords C/S; chating system; TCP / IP protocol; JSP目录摘要 (I)Abstract (II)第1章绪论 (1)1.1课题研究背景 (1)1.2基本技术支持 (1)1.2.1 ASP简介 (1)1.2.2 HTML简介 (3)第2章需求分析 (5)2.1功能需求 (5)2.2 性能需求 (5)2.3可行性分析 (6)2.3.1技术可行性 (6)2.3.2操作可行性 (7)2.3.3经济与技术可行性 (7)第3章总体设计 (8)3.1软件运行环境设计 (8)3.2功能介绍 (8)3.2.1功能结构设计 (8)3.2.2系统模块设计 (9)3.3 数据库设计 (10)第4章详细设计 (11)4.1用户登录模块的设计 (11)4.2新用户注册模块的设计 (13)4.3密码修改模块的设计 (14)4.4聊天者发言模块设计 (15)4.4.1用户聊天时的具体设计 (16)4.4.3显示发言信息模块设计 (18)4.4.3显示在线用户模块设计 (19)4.4.4用户离开聊天室的设计 (19)4.5数据库结构设计 (20)第5章测试与性能分析 (22)总结 (25)致 (26)参考文献 (27)附录A (28)附录B (35)第1章绪论1.1课题研究背景随着Internet的普及和宽带技术的成熟,越来越多的用户进入到网络世界中享用浏览新闻、查询信息、发送、在线观看电影等服务,享受网络带来的便利和办公的高效。
C#课程设计简单的聊天室工具系统

郑州科技学院C#课程设计论文题目:简单的聊天室工具院系:信息工程学院专业:计算机科学与技术班级:10计科二班姓名:李海朋学号:201015050日期:2013-5-30摘要随着网络的出现,信息资源的实时共享成为现实,更重要的是它提供了一种极为直接的交互方式,当然这种交互不单是指数据、信息之间的传递,也包括人与人之间的互相交流,各种聊天软件和在线聊天室正是承载这类交互的媒介。
简单的聊天室工具程序是一种比较流行色C/S模式的聊天工具设计,基于C#进行程序的简单设计。
C/S(Client/Server,客户机/服务器)模式又称C/S结构,是软件系统结构的一种。
C/S模式简单的讲就是基于企业内部网络的应用系统。
与B/S(Browser/Server,浏览器/服务器)模式相比,C/S模式的应用系统最大的好处是不依赖企业外网环境,即无论企业是否能上网都不影响使用(基于局域网)。
简单的聊天室工具主要聊天室客户端和聊天室服务器组成。
其中聊天室服务器负责管理与客户端的连接并发送消息给客户端,聊天室客户端负责接收或者发送聊天信息、登陆聊天室服务器等。
关键技术Socket,所谓Socket通常也称为“套接字”,它是通信的基础,用于描述IP地址和端口,一个套接字是通信的一端,在这一端上可以找到与其对应的一个名字,一个正在被使用的套接字都有它的类型和与其相关的进程。
套接字存在于通信域。
通信域是为了处理一般的线程通过套接字通信而引进的一种抽象概念。
套接字通常和同一个域中的套接字交换数据(数据交换也可以穿越域的界限,但是这时需要执行莫种解释程序)。
它也可以说是一个通信链的句柄。
应用程序通常通过套接字向网络发出请求或者应答网络请求。
研究人员为TCP/IP网络通信开发了一个API (应用程序接口)。
这个API称为Socket接口(套接字)。
目录1概述 (4)1.1开发背景 (4)1.1.1 各种聊天工具的兴起 (4)1.1.2本系统开发环境 (5)1.1 C#语言的发展 (5)2 C/S聊天模型设计 (6)2.1 服务器/客户端聊天模型 (6)2.2 服务器/客户端消息传递模型 (7)3聊天协议 (8)3.1关于聊天协议的应答 (8)3.2 聊天状态处理 (9)3.3 聊天命令介绍 (9)3.3.1 CONNECT命令 (9)3.3.2 JOIN命令 (10)3.3.3 LIST命令 (10)3.3.4 CHAT命令 (11)3.3.5 PRIV命令 (11)3.3.6 EXIT和QUIT命令 (11)4 系统功能定义 (12)4.1 聊天工具服务器 (12)4.2 聊天工具客户端 (13)5 系统功能设计 (14)5.1聊天工具服务器的协议解析流程图 (14)5.2聊天工具客户端的协议解析流程 (16)6系统功能实现 (17)6.1 服务器端程序设计 (17)6.1.1类和成员定义的以及构造函数 (17)6.1.2获得有效的端口号和IP地址 (18)6.1.3启动聊天工具服务器 (20)6.1.4关于ChatClient类的定义 (23)6.1.5聊天命令的处理 (24)6.2客户端程序设计 (31)6.2.1类的成员定义及构造函数 (31)6.2.2与聊天工具服务器的连接 (32)6.2.3聊天信息的发送 (34)6.2.4聊天命令处理 (36)6.2.5退出聊天 (39)7 聊天工具程序的运行与测试 (40)总结 (44)参考文献 (45)1概述1.1开发背景1.1.1 各种聊天工具的兴起随着网络的出现,信息资源的实时共享成为现实,更重要的是它提供了一种极为直接的交互方式,当然这种交互不单是指数据、信息之间的传递,也包括人与人之间的互相交流,各种聊天软件和在线聊天室正是承载这类交互的媒介。
基于CS简单聊天程序课程设计

(2)启动服务器;
(3)关闭服务器;
(4)用户之间的聊天;
(5)退出聊天室。
本系统其体功能需求如下:
(1)聊天室管理员经登录界面登录到管理界面,即系统的服务器端。用户经登录界面进入聊天大厅。
(2)不论就是管理员还就是用户都需要在登录界面输入正确的用户名与密码后才可以登录到各自的界面中去。
进
度
安
排
起止日期
工作内容
6、13-6、18
设计聊天室的模型,布局
6、19-6、20
编写代码,初步实现聊天程序
6、21-6、26
完善代码,优化界面,完成任务
主
要
参
考
资
料
[1]赵生慧、《Java面向对象程序设计》(第二版)[M]、北京:中国水利水电出版社,2013、
[2]万常选、《数据库系统原理与设计》(第二版)[M]、北京:清华大学出版社,2012、
(6)服务器状态,聊天信息与在线用户人数及时刷新。
(7)聊天室系统运行稳定、安全性高、
三、过程论述
3、1 服务器端
(1)首先实现的就是服务器开始工作界面,如图3-1所示:
图3-1
代码如下:
public ChatServer() {
try {
System、out、println("服务器开始工作、、、、、、");
server=new ServerSocket(port);//初始化服务器套接字
while (true){
socket=server、accept();//等待连接
System、out、println(socket、getInetAddress()+"连接\n");//得到客户机地址
课程设计简易聊天程序设计

课程设计报告课程名称:面向对象程序设计 C++设计题目:简易聊天程序设计专业:计算机科学与技术______ 姓名:金文指导教师:李晓虹2015 年1 月10 日(一)系统需求分析用户角度考察系统应具有哪些功能及非功能性需求。
能实现用户注册、用户的登录、各客户端能连接起来,服务器能与客户端相连实现用户之间信息的发送与共享。
(二)总体设计1初始化socket,创建服务器端2、维护一个链表,保存所有用户的IP地址、端口信息3、接受用户传送来的聊天信息,然后向链表中的所用用户转发4、接受用户传送来的连接判断命令,并向用户发出相应命令根据连接启动的方式以及本地套接字要连接的目标,套接字之间的连接过程可以分为三个步骤:服务器监听,客户端请求,连接确认。
建立服务器显示本机IP地址建立连接提示连接成功J#*"""-在另一台机器上运行聊天程序Jr.进行聊天输入服务器IP地址清除聊天输入名子建立聊天关闭服务器提示连接成功或失败提示有某个服务器正在连接,是否连接进行聊天退出清除聊天内容断开连接(三)详细设计ChatClient:运行界面:名 I 金文珍T____ .. ___________________________________ _________________________________________ I服务 127.0.0,1!鬧疋■nn去 |6 勺 取消连接服务器:IDD_SENDDLG重要代码:void CChatClientDoc::talk(int type, CString form, CString to, CString str, COLORREF clr){CChatClientView* pView = (CChatClientView*)GetView();if(form != m_strHandle && to != m_strHandle && m_bFilter) return;CString temp,to2,first,second;if(type > 32 || type < 0)return;temp.LoadString(IDS_TALKO + type);int i=temp.Find(",");if(i != -1){first = temp.Left(i);if(i != temp.GetLength() - 1){second = temp.Mid(i + 1); second +="";}else{ second="";}pView->TextOut((LPCTSTR)form, RGB(0,0,255)); pView->TextOut((LPCTSTR)first,RGB(0,0,0)); pView->TextOut((LPCTSTR)to, RGB(0,0,255));pView->TextOut((LPCTSTR)second, RGB(0,0,0)); pView->TextOut((LPCTSTR)str,clr);pView->TextOut((LPCTSTR)"\r\n,,,clr);}else{first=temp; second=":"; pView->TextOut(form,RGB(0,0,255));pView->TextOut(first,RGB(O,O,O)); pView->TextOut(second,RGB(0,0,0));pView->TextOut(str,clr); pView->TextOut("\r\n",clr);}}void CChatClientDoc::Disconnect(){msg.type = -2;msg.m_bClose = TRUE;msg.from = m_strHandle;msg.to = "所有人";msg.secret = FALSE;msg.m_strText ="Hello";msg.color = RGB(0,136,255);SendMsg();m_bConnected = FALSE;msg.from = "DUMP";GetView()->GetParent()->SendMessage(WM_ADDLIST + 1, (LPARAM)&(msg.from), msg.image); }void CChatClientView::TextOut(LPCTSTR lpszMessage, COLORREF clr){cfm.cbSize=sizeof(cfm); // CHARFORMAT cfm cfm.crTextColor=clr; cfm.dwMask=CFM_COLOR;CString strTemp = lpszMessage;int len = GetWindowTextLength();GetRichEditCtrl().SetSel(len,len);GetRichEditCtrl().SetSelectionCharFormat(cfm);GetRichEditCtrl().ReplaceSel(strTemp);}void CChatSocket::OnReceive(int nErrorCode){CSocket::OnReceive(nErrorCode);m_pDoc->ProcessPendingRead();}void CChatClientCntrItem::Dump(CDumpContext& dc) const{CRichEditCntrItem::Dump(dc);}void CLogin::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CLogin)DDX_CBString(pDX, IDC_IMAGE, m_strImage);DDX_CBString(pDX, IDC_NAME, m_strName);DDX_Text(pDX, IDC_SERVER, m_strServerIP); //}}AFX_DATA_MAP}BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) {if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE;cs.style &= ~WS_MAXIMIZEBOX;cs.style &= ~WS_SIZEBOX;cs.cx = 640;cs.cy = 480;return TRUE;}CMessage::CMessage(){image = 6;type = 0;secret = FALSE;color = RGB(0,136,255);m_bClose = FALSE;from = to = m_strText = _T("");}CMessage::~CMessage(){}void CMessage::Serialize(CArchive &ar) {if (ar.IsStoring()){ar <<type;ar <<(WORD)m_bClose; ar <<m_strText;ar <<(WORD)secret; ar <<from;ar <<to;ar <<(DWORD)color;ar <<image;}else{WORD wd;DWORD dwTmp;ar >>type;ar >>wd;m_bClose = (BOOL)wd;ar >>m_strText;ar >>wd; secret = (BOOL)wd;ar >>from;ar >>to;ar >>dwTmp;color = (COLORREF)dwTmp;ar >>image;}/*m_msgList.Serialize(ar); fromlist.Serialize(ar); tolist.Serialize(ar);seclist.Serialize(ar); typelist.Serialize(ar); clrlist.Serialize(ar);*/} void CMessage::Reset(){image = 6;type = 0; secret = FALSE;color = RGB(0,136,255); m_bClose = FALSE;from = to = m_strText = _T("");/* m_msgList.RemoveAll(); fromlist.RemoveAll(); tolist.RemoveAll(); seclist.RemoveAll();clrlist.RemoveAll(); typelist.RemoveAll();*/}int COnlineBar::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CDialogBar::OnCreate(lpCreateStruct) == -1) return -1;CRect rect;GetClientRect(&rect);rect.left += 8;rect.top += 15;rect.right -= 8;rect.bottom -= 8;m_ListCtrl = new COnlineList;if (!m_ListCtrl->Create(WS_CHILD | WS_VISIBLE | LVS_REPORT, rect, this, IDC_LISTBOX)) {TRACE0("Failed to create view for CMyBarLeft\n"); return -1;}m_ListCtrl->ModifyStyleEx(0, WS_EX_CLIENTEDGE); AddExStyle(LVS_EX_FULLROWSELECT | LVS_OWNERDRAWFIXED);int i;LV_COLUMN lvc;lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; CString strTemp[2] = {"名称", "IP"};int size[2] = {140,40};for(i = 0; i < 2; i++){ lvc.iSubItem = i; lvc.pszText = (char*)(LPCTSTR)strTemp[i]; lvc.cx = size[i];lvc.fmt = LVCFMT_LEFT; m_ListCtrl->InsertColumn(i, &lvc);}return 0;}void COnlineBar::AddExStyle(DWORD dwNewStyle) {DWORD dwStyle = ::SendMessage (m_ListCtrl->m_hWnd, LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0);dwStyle |= dwNewStyle;::SendMessage (m_ListCtrl->m_hWnd, LVM_SETEXTENDEDLISTVIEWSTYLE,0, dwStyle);}int COnlineList::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CListCtrl::OnCreate(lpCreateStruct) == -1) return -1;m_imgList.Create(IDB_IMAGE, 16, 1, RGB(0, 255, 0));HIMAGELIST him = m_imgList.m_hImageList;::SendMessage(this->m_hWnd,LVM_SETIMAGELIST,(WPARAM)LVSIL_SMALL,(LPARAM )him);//::SendMessage(this->m_hWnd,LVM_SETIMAGELIST,(WPARAM)LVSIL_NORMAL,(LPAR AM)him);ImageList_SetBkColor(him,CLR_NONE);return 0;}void COnlineList::AddItem(short i, char* name, char* text){LVITEM lvi;lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;lvi.iItem = GetItemCount();lvi.iImage = i;lvi.iSubItem = 0;lvi.pszText = name;hTextMax = 64;lvi.lParam = 0;InsertItem(&lvi);lvi.mask = LVIF_TEXT;lvi.pszText = text;hTextMax = 32;lvi.iSubItem = 1;SetItem(&lvi);}void COnlineList::OnDblclk(NMHDR* pNMHDR, LRESULT* pResult){NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;CString str;int iSel = pNMListView->iItem;if (iSel >= 0 ){str = GetItemText(iSel,0);CWnd* pParentWnd = GetParent(); while (pParentWnd != NULL){ if(pParentWnd->IsFrameWnd()){ break;} pParentWnd = pParentWnd->GetParent();}if (pParentWnd != NULL) pParentWnd->SendMessage(WM_DBCLICKITEM, 0, (LPARAM)&str);}*pResult = 0;}void COnlineList::Remove(char *name){CString str;for(int i = 0; i <GetItemCount(); i++){str = GetItemText(i,0); if(strcmp(str, name) == 0){ DeleteItem(i); break;}}}Charsrv:r 菜单设计( IDR_MAINFRAME)对话框设计:IDD ABOUTBOX'请畴簧矚出聊天室的人名On UpdateCo nn ectio ns(CCmdUI* pCmdUI)On UpdateMessages(CCmdUI* pCmdUI) ProcessPendin gAccept()ProcessPe ndin gRead(CClie ntSocket* pSocket)ReadMsg(CClie ntSocket* pSocket)SendMsg(CCIientSocket* pSocket, CMessage*pMsg)Serialize(CArchive &ar)talk(int type2, CString from1, CString to1,CStri ng str1)UpdateClie nts()类名相关变量相关函数CServerView AssertValid() constCServerView()~CServerView()Dump(CDumpC on text &dc) const CServerDoc*CServerView::GetDocume nt() Message(LPCTSTRlpszMessage) Message1(LPCTSTR lpszMessage)On Draw(CDC* pDC)相关代码:void CAboutDlg::DoDataExcha nge(CDataExcha nge* pDX) {CDialog::DoDataExcha nge(pDX);//{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP} CCleanDlg::CCleanDlg(CWnd* pParent /*=NULL*/)ss-相关图标:: CDialog(CCleanDlg::IDD, pParent){//{{AFX_DATA_INIT(CCleanDlg) m_cleanname = _T("");//}}AFX_DATA_INIT}// CClientSocket ConstructionCClientSocket::CClientSocket(CServerDoc* pDoc){m_pDoc = pDoc; m_nMsgCount = 0; m_pFile = NULL;m_pArchiveIn = NULL; m_pArchiveOut = NULL;needdel=false;}/////////////////////////////////////////////////////////////////////////////// CClientSocket Operationsvoid CClientSocket::Init(){m_pFile = new CSocketFile(this);m_pArchiveIn = new CArchive(m_pFile,CArchive::load); m_pArchiveOut = newCArchive(m_pFile,CArchive::store);}void CClientSocket::Abort(){if (m_pArchiveOut != NULL){ m_pArchiveOut->Abort(); delete m_pArchiveOut; m_pArchiveOut = NULL;}}void CClientSocket::SendMsg(CMessage* pMsg){if (m_pArchiveOut != NULL){pMsg->Serialize(*m_pArchiveOut);m_pArchiveOut->Flush();}}void CClientSocket::ReceiveMsg(CMessage* pMsg){pMsg->Serialize(*m_pArchiveIn);}/////////////////////////////////////////////////////////////////////////////// CClientSocket Overridable callbacksvoid CClientSocket::OnReceive(int nErrorCode){CSocket::OnReceive(nErrorCode);m_pDoc->ProcessPendingRead(this);}BOOL CClientSocket::HasConnectionDropped( void ){BOOL bConnDropped = FALSE;INT iRet = 0;BOOL bOK = TRUE;struct timeval timeout = { 0, 0 };fd_set readSocketSet;FD_ZERO( &readSocketSet );FD_SET( m_hSocket, &readSocketSet );iRet = ::select( 0, &readSocketSet, NULL, NULL, &timeout );bOK = (iRet > 0);if(bOK){bOK = FD_ISSET( m_hSocket, &readSocketSet );}if( bOK ){CHAR szBuffer[1] = "";iRet = ::recv( m_hSocket, szBuffer, 1, MSG_PEEK ); bOK = ( iRet > 0 );if( !bOK ){INT iError = ::WSAGetLastError(); bConnDropped = ( ( iError == WSAENETRESET )|| ( iError == WSAECONNABORTED ) || ( iError == WSAECONNRESET ) || ( iError ==WSAEINVAL ) || ( iRet == 0 ) ); //Graceful disconnect from other side.}}return( bConnDropped );}/////////////////////////////////////////////////////////////////////////////// CSocket ImplementationCClientSocket::~CClientSocket(){if (m_pArchiveOut != NULL)delete m_pArchiveOut;if (m_pArchiveIn != NULL)delete m_pArchiveIn;if (m_pFile != NULL)delete m_pFile;}#ifdef _DEBUGvoid CClientSocket::AssertValid() const{CSocket::AssertValid();}void CClientSocket::Dump(CDumpContext& dc) const{CSocket::Dump(dc);}///////////////////////////////////////////////////////////////////////////// // CSocket ImplementationCListeningSocket::~CListeningSocket(){}#ifdef _DEBUGvoid CListeningSocket::AssertValid() const{CSocket::AssertValid();}void CListeningSocket::Dump(CDumpContext& dc) const{CSocket::Dump(dc);}LRESULT CMainFrame::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) {LRESULT result = CFrameWnd::WindowProc(message, wParam, lParam);if(wParam == SC_MINIMIZE){ShowWindow(SW_HIDE);}return result;}void CMainFrame::OnClose(){Shell_NotifyIcon(NIM_DELETE, &pnid);CFrameWnd::OnClose();}void CMainFrame::OnRestore(){}void CMainFrame::OnKickout(){CServerDoc* pDoc = (CServerDoc*)GetActiveDocument(); pDoc->Clean();}void CMessage::Serialize(CArchive &ar){if (ar.IsStoring()){ar <<type;ar <<(WORD)m_bClose;ar <<m_strText;ar <<(WORD)secret;ar <<from;ar <<to;ar <<(DWORD)color;ar <<image;}else{WORD wd;DWORD dwTmp;ar >>type;ar >>wd;m_bClose = (BOOL)wd;ar >>m_strText;ar >>wd;secret = (BOOL)wd;ar >>from;ar >>to;ar >>dwTmp;color = (COLORREF)dwTmp;ar >>image;}}void CServerDoc::UpdateList(CClientSocket* pSocket){CMessage* pMsg = new CMessage;for(POSITION pos = m_connectionList.GetHeadPosition(); pos != NULL;){CClientSocket* pSock = (CClientSocket*)m_connectionList.GetNext(pos); pMsg->from = pSock->name;pMsg->type = -8;pMsg->image = pSock->image;SendMsg(pSocket, pMsg);}}void CServerView::OnDraw(CDC* pDC){CServerDoc* pDoc = GetDocument();ASSERT_VALID(pDoc);}四)系统调试服务器的是聊天系统中很重要的部分,这个界面设计较为简单,对客服端信息的发送时,问题接二连三的出现,很多都出现异常,主要是由于在定义语句不小心出现专业术语错误。
CS模式网络聊天小程序实验报告

南华大学船山学院实验报告(2010 ~2011 学年度第1 学期)课程名称Java实验名称C/S模式网络聊天小程序专业计算机科学班级09级01班与技术地点8-209 指导老师谢卫星一、设计分析:1.预设界面:界面主要包含文本输出框,文本输入框,ip显示标签或者是文本框,端口显示标签Client选择按钮,Server选择按钮,ip设置按钮,Client/Server重设按钮。
预测界面如下:2.主要程序预测:主程序包括服务端与客户端,服务端包括serversocket的创建,绑定端口,监听线程,发送数据到各个客户端以及关闭socket。
客户端包括创建socket,发送数据到服务器。
二、流程分析:1.界面流程分析:a.定义一个主容器;b.主容器里定义三个容器(用于文本输出,文本输入,设置);c.设置容器包含ip和端口显示文本框,ip设置,Client,Server以及重选按钮;d.编写窗口事件监听程序。
2.服务器流程分析:a.定义一个服务线程,包括serversocket创建,用于记录客户端信息的可变数组。
b.定义一个监听方法,监听输入输出流。
c.定义发送信息到各个客户端方法与移除客户端信息方法。
d. 调用serversocket的accept函数用于接收客户端连接信息,然后创建一个监听线程,监听到客户端信息后发送到各个客户端,最后移除客户端信息。
3.客户端流程分析:a)定义一个客户线程,包括clientsocket创建,输入输出流的定义。
b)当客户端连接到服务器时,创建clientsocket,建立输入输出流。
c)利用输入输出流接收服务器数据,发送客户端的信息。
三、参考资料:《面向对象程序设计——java》、《JA V A API官方文档中文版.CHM》。
四、程序源代码:import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.io.DataInputStream;import java.io.DataOutputStream;import .ServerSocket;import .Socket;import java.util.Vector;public class Client implements ActionListener{JFrame frame=null;TextArea text=new TextArea(10,50);TextArea text1=new TextArea(10,50);TextField text2=new TextField(2);TextField text3=new TextField("端口:",2);JButton button=new JButton("发送");JButton ServerBtn,ClientBtn,button3,bstop;JPanel panel,panel1;JLabel label=new JLabel("copy right by 2010.502-5 ");Container cp;boolean bool=false;boolean ServerOrNot=false;boolean ClientOrNot=false;String str1=null,clientName=null,title="Warnning",content=null;DataOutputStream SendMessage;DataInputStream RcvMessage;Socket buffersocket;String msg;public Client(){frame=new JFrame("聊天软件");cp=frame.getContentPane();BorderLayout layout=new BorderLayout();cp.setLayout(layout);panel=new JPanel(new GridLayout(3,0,0,30));text.setEditable(false);//设置文本域为只读text1.setBackground(Color.white);button.setBackground(Color.yellow);button.setForeground(Color.red);button.addActionListener(this);text2.setText("127.0.0.1");text2.setEditable(false);panel.add(text2);text3.setText("端口:7788");text3.setEditable(false);panel.add(text3);button3=new JButton("IP设置");button3.addActionListener(this);panel.add(button3);ServerBtn=new JButton("Server");ServerBtn.addActionListener(this);panel.add(ServerBtn);ClientBtn=new JButton("Client");ClientBtn.addActionListener(this);panel.add(ClientBtn);bstop=new JButton("stop");bstop.addActionListener(this);panel.add(bstop);panel1=new JPanel(new FlowLayout());panel1.add(label);panel1.add(button);cp.add(text,BorderLayout.NORTH);cp.add(text1,BorderLayout.CENTER);cp.add(panel,BorderLayout.EAST);cp.add(panel1,BorderLayout.SOUTH);frame.pack();frame.setVisible(true);}public static void main(String[] args) {new Client();}public void actionPerformed(ActionEvent e){String cmd=e.getActionCommand();String ip;if(cmd.equals("发送")){if(bool==true){str1=text1.getText();if(str1.equals("")){JOptionPane.showMessageDialog(frame,"Warnning:消息不能为空",title,JOptionPane.W ARNING_MESSAGE);}else {if( ClientOrNot){try{content="【"+clientName+"】"+"对大家说:"+str1;SendMessage.writeUTF(content);content=null;}catch (Exception ex){JOptionPane.showMessageDialog(frame,"Warnning:消息发送错误"+ex.getMessage(),title,JOptionPane.W ARNING_MESSAGE);}}else if(ServerOrNot){JOptionPane.showMessageDialog(frame,"Warnning:服务器无法发送信息",title,JOptionPane.W ARNING_MESSAGE);}text1.setText("");}}else {JOptionPane.showMessageDialog(frame,"Warnning:请先设置Server或Client",title,JOptionPane.W ARNING_MESSAGE);}}if(cmd.equals("IP设置")){ip=(String)JOptionPane.showInputDialog(frame,"请输入服务器链接IP",cmd,JOptionPane.PLAIN_MESSAGE);text2.setText(ip);}if(cmd.equals("Server")){JOptionPane.showMessageDialog(frame,"创建服务器!",cmd,JOptionPane.PLAIN_MESSAGE);ClientBtn.setEnabled(false);button3.setEnabled(false);clientName="主机";bool=true;ServerOrNot=true;servertest serverthread=new servertest();}if(cmd.equals("Client")){clientName=JOptionPane.showInputDialog(frame,"你选择了客户端,输入用户名:",cmd,JOptionPane.PLAIN_MESSAGE);if(clientName.equals("")){JOptionPane.showMessageDialog(frame,"Warnning:用户名不能为空"+clientName,title,JOptionPane.W ARNING_MESSAGE);}else if(clientName.equals("主机")){JOptionPane.showMessageDialog(frame,"Warnning:用户名不能取为"+clientName,title,JOptionPane.W ARNING_MESSAGE);}else {if(ClientOrNot==true){JOptionPane.showMessageDialog(null,"你已经连接到服务器了!","提示",JOptionPane.W ARNING_MESSAGE);}try{clienttest connectthread=new clienttest (this);ServerBtn.setEnabled(false);}catch (Exception ex){ServerBtn.setEnabled(true);JOptionPane.showMessageDialog(null,"连接服务器错误!","提示",JOptionPane.W ARNING_MESSAGE);}bool=true;}}if(cmd.equals("stop")){bool=false;ServerOrNot=false;ClientOrNot=false;clientName=null;try{ClientBtn.setEnabled(true);button3.setEnabled(true);ServerBtn.setEnabled(true);}catch(Exception ex){JOptionPane.showMessageDialog(null,"stop"+ex.getMessage(),"提示", JOptionPane.ERROR_MESSAGE);}}}//服务器线程class servertest extends Thread{ServerSocket serversocket;Socket clientsocket;DataInputStream in;DataOutputStream out;Vector vClient;servertest(){try{serversocket = new ServerSocket(7788); //构造socket;vClient=new Vector(); //可增长数组记录客户端信息}catch(Exception e){JOptionPane.showMessageDialog(null,"启动服务失败,"+e.getMessage(),"提示", JOptionPane.ERROR_MESSAGE);return;}this.start();}public void run(){while(ServerOrNot){try{serversocket.setSoTimeout(100); //设置超时时间clientsocket = serversocket.accept();//接受客户端信息ListenThread listenthread=new ListenThread(this);//监听函数vClient.addElement(listenthread);//加入客户端信息}catch(Exception e){}}try{serversocket.close();//关闭线程JOptionPane.showMessageDialog(frame,"关闭服务器",title,JOptionPane.W ARNING_MESSAGE);}catch(Exception e){}}//监听线程class ListenThread extends Thread{servertest servertest;DataInputStream in;DataOutputStream out;Socket clientsocket;ListenThread(servertest servertest){this.servertest=servertest;this.clientsocket=servertest.clientsocket;try{in=new DataInputStream(clientsocket.getInputStream());out=new DataOutputStream(clientsocket.getOutputStream());clientsocket=servertest.clientsocket;}catch(Exception e){//JOptionPane.showMessageDialog(null,"listen,"+e.getMessage(),"提示", JOptionPane.ERROR_MESSAGE);}this.start();}public void run(){String rcv="";while(ServerOrNot){try{rcv=in.readUTF();//从输入流读取数据SMessage(rcv);//发送数据到各个客户端text.append(rcv+"\n");}catch(Exception e){break;}}try{SMessage("失去连接");//发送数据到各个客户端text.append("服务器失去连接"+"\n");RemoveConnect(this);//移除客户端信息}catch(Exception ex){}}}// 移除客户端信息public synchronized void RemoveConnect(ListenThread listenthread){try{listenthread.clientsocket.close();vClient.removeElementAt(vClient.indexOf(listenthread));}catch(Exception e){}}// 发送数据到各个客户端public synchronized void SMessage(String message){try{for(int i=0;i<vClient.size();i++){ListenThread listenthread = (ListenThread) vClient.elementAt(i);listenthread.out.writeUTF(message);}}catch(Exception e){return;}}}//客户端线程class clienttest extends Thread{Client mainwnd;DataInputStream in;clienttest (Client wnd) {this.mainwnd=wnd;mainwnd.text.append(mainwnd.text2.getText());try{mainwnd.buffersocket=new Socket(mainwnd.text2.getText(),7788);//建立发送socketmainwnd.RcvMessage=newDataInputStream(mainwnd.buffersocket.getInputStream());mainwnd.SendMessage=newDataOutputStream(mainwnd.buffersocket.getOutputStream());mainwnd.text.append("成功连接到服务器\n");mainwnd.ClientOrNot=true;}catch(Exception e){mainwnd.text.append("连接服务器失败!"+e.getMessage()+"\n");}this.start();}public void run(){String rec="";while(ClientOrNot){try{mainwnd.buffersocket.setSoTimeout(100);rec=mainwnd.RcvMessage.readUTF();mainwnd.text.append(rec+"\n");}catch(Exception e){}}JOptionPane.showMessageDialog(frame,"关闭客户端!",title,JOptionPane.W ARNING_MESSAGE);}}}五、运行结果:六、程序测试:1、设置服务端:打开运行程序—>单击Server设置为客户端2、设置客户端:ip设置(设置成连接主机的ip)——>启动Client并设置用户名——>发送消息——>成功发送或发送超时。
基于CS简单聊天程序课程设计报告

计算机网络课程设计任务书基于C/S模式的简单聊天程序设计说明书学院名称:计算机与信息工程学院班级名称:网络工程142学生XX:三学号:2014211540题目:基于C/S模式的简单聊天程序指导教师姓名:海宝起止日期:2016.6.13-2016.6.26目录一、选题背景1二、方案论证1三、过程论述23.1 服务器端23.2 客户机端10四、结果分析20五、结论21第一部分:正文部分一、选题背景使用Socket实现网上聊天功能。
用户可以通过客户端连接到服务器端并进行网上聊天。
聊天时可以启动多个客户端。
服务器端启动后,接收客户端发来的用户名和密码验证信息。
验证通过则以当前的聊天客户列表信息进行响应;此后接收客户端发来的聊天信息,转发给客户端指定的聊天客户(即私聊)或所有其他客户端;在客户断开连接后公告其退出聊天系统的信息。
客户端启动后在GUI界面接收用户输入的服务器端信息、账号和密码等验证客户的身份。
验证通过则显示当前系统在线客户列表。
客户可以与指定对象进行私聊,也可以向系统中所有在线客户发送信息。
二、方案论证基于C/S的简单聊天室可以实现用户与服务器间,服务器与多个用户间的通信。
聊天室程序通常需要完成以下一些基本功能:(1)登录聊天室;(2)启动服务器;(3)关闭服务器;(4)用户之间的聊天;(5)退出聊天室。
本系统其体功能需求如下:(1)聊天室管理员经登录界面登录到管理界面,即系统的服务器端。
用户经登录界面进入聊天大厅。
(2)不论是管理员还是用户都需要在登录界面输入正确的用户名和密码后才可以登录到各自的界面中去。
(3)系统的两个主要界面都是为方便管理员和用户操作的。
首先,管理员进入到管理界面后可以方便的启动/停止服务器,看到在线用户的信息和聊天信息。
用户进入到聊天大厅中可以聊天,查看服务器状态。
(4)一个用户退出聊天室对其他用户不能产生影响,而服务器断开与客户端的连接则所有的用户都失去与服务器的连接。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
sendClients(newUser);
}
public static void sendClients(StringBuffer message){
for(int i =0;i<clients.size();i++)
{
Client client=(Client)clients.elementAt(i);
(1)登录聊天室;
(2)启动服务器;
(3)关闭服务器;
(4)用户之间的聊天;
(5)退出聊天室。
本系统其体功能需求如下:
(1)聊天室管理员经登录界面登录到管理界面,即系统的服务器端。用户经登录界面进入聊天大厅。
(2)不论是管理员还是用户都需要在登录界面输入正确的用户名和密码后才能够登录到各自的界面中去。
(6)服务器状态,聊天信息和在线用户人数及时刷新。
(7)聊天室系统运行稳定、安全性高、
三、过程论述
3.1 服务器端
(1)首先实现的是服务器开始工作界面,如图3-1所示:
图3-1
代码如下:
public ChatServer() {
try {
System.out.println("服务器开始工作......");
图3-2
代码如下:
public static void notifyChatRoom(){
StringBuffer newUser=new StringBuffer("newUser");
for(int i =0;i<clients.size();i++){
Client c=(Client)clients.elementAt(i);
[3]谢钧,谢希仁.《计算机网络教程》(第四版)[M].北京:人民邮电出版社, .
[4]李刚.《疯狂JAVA讲义》[M].(第三版).北京:电子工业出版社, .
[5]耿祥义、张跃平.《Java2实用教程》[M].(第三版).北京:清华大学出版社, .
[6]刘海杰.《Java编程设计》[M].北京:中国铁道出版社, .
进
度
安
排
起止日期
工作内容
6.13-6.18
设计聊天室的模型,布局
6.19-6.20
编写代码,初步实现聊天程序
6.21-6.26
完善代码,优化界面,完成任务
主
要
参
考
资
料
[1]赵生慧.《Java面向对象程序设计》(第二版)[M].北京:中国水利水电出版社, .
[2]万常选.《数据库系统原理与设计》(第二版)[M].北京:清华大学出版社, .
指导教师
意见
(签字):年月日
系(教研室)主任意见
(签字): 年月日
基于C/S模式的简单聊天程序设计说明书
பைடு நூலகம்学院名称:计算机与信息工程学院
班级名称:网络工程142
学生姓名:张 三
学 号:211540
题 目:基于C/S模式的简单聊天程序
指导教师
姓 名:陈 海 宝
起止日期:.6.13- .6.26
第一部分:正文部分
点击“连接”按钮实现与服务器的连接。点击“断开”按钮实现与服务器的断开连接。
(2)服务器聊天室具有启动服务器,停止服务器,显示当前在线的用户功能。点击“启动”按钮实现与服务器的连接。点击“停止”按钮实现与服务器的断开连接。
(3)设计一个登录程序。验证经过后才能进入聊天室。
(4)当服务器与客户机连接成功后。能够互相接受和发送消息。当多个客户机启动时,服务器会创立子线程处理对应线程的消息。三、项目设计(研究)思路
(1)设计步骤:先画出聊天室的模型,布局。
(2)设计要点:设计主类与子类,分别实现不同的功能
(3)主要技术分析:需要掌握socket通信,swing和awt,io的简单应用.
(4)解决思路:先按照草稿图设计出聊天室布局。再写各个类的功能。简单测试与修改代码。最后完善。
四、具体成果形式和要求
(见第一部分)
基于CS简单聊天程序课程设计
计算机网络课程设计任务书
学 院
计算机与信息工程学院
专 业
网络工程
课程名称
计算机网络
题 目
基于C/S模式的简单聊天程序
完成期限
自6月13日至6月26日共两周
内
容
及
任
务
一、项目的目的
利用socket。实现客户与服务器间的信息互通。
二、项目任务的主要内容和要求
(1)用户聊天室具有群发,私聊,输入昵称与端口号等基本设置。
客户端启动后在GUI界面接收用户输入的服务器端信息、账号和密码等验证客户的身份。验证经过则显示当前系统在线客户列表。客户能够与指定对象进行私聊,也能够向系统中所有在线客户发送信息。
二、方案论证
基于C/S的简单聊天室能够实现用户与服务器间,服务器与多个用户间的通信。
聊天室程序一般需要完成以下一些基本功能:
一、选题背景
使用Socket实现网上聊天功能。用户能够经过客户端连接到服务器端并进行网上聊天。聊天时能够启动多个客户端。
服务器端启动后,接收客户端发来的用户名和密码验证信息。验证经过则以当前的聊天客户列表信息进行响应;此后接收客户端发来的聊天信息,转发给客户端指定的聊天客户(即私聊)或所有其它客户端;在客户断开连接后公告其退出聊天系统的信息。
clients.add(client);//增加客户线程到向量中
client.start();//启动线程
notifyChatRoom();//监视聊天室连接变化
}
}catch(Exception ex){
ex.printStackTrace();
}
}
(2)监视聊天室连接情况,并显示出来,如图3-2所示:
server=new ServerSocket(port);//初始化服务器套接字
while (true){
socket=server.accept();//等待连接
System.out.println(socket.getInetAddress()+"连接\n");//得到客户机地址
Client client=new Client(socket);//实例化一个客户线程(其中线程Client中Socket,这里的Socket只是起个过渡作用)
(3)系统的两个主要界面都是为方便管理员和用户操作的。首先,管理员进入到管理界面后能够方便的启动/停止服务器,看到在线用户的信息和聊天信息。用户进入到聊天大厅中能够聊天,查看服务器状态。
(4)一个用户退出聊天室对其它用户不能产生影响,而服务器断开与客户端的连接则所有的用户都失去与服务器的连接。
(5)用户的聊天信息录入,重写,发送,接收方便,快捷。