网络编程聊天室主要代码

合集下载

C#.net聊天室制作代码

C#.net聊天室制作代码

2012-2-6聊天室制作流程:建立发送页面send.aspx,显示页面showmessage.aspx,主要是这两个,还可以加显示所以用户名字exit.aspx;思路:聊天室要用到数据库,所以在发送页面需要做的是把用户填好的东西加入到数据库储存起来。

到显示页面和显示所以用户页面就顺理成章的把数据库用户填写的信息读取出来这就构成了一个聊天室的主要骨架。

第一个发送页面send.aspx前台代码:<body><form id="form1"runat="server"><div></div><br/><table align="center"width="600"height="150"><tr><td><strong><span style="color: #ff00ff">内容:</span></strong></td><td><asp:TextBox ID="TextBoxContent"Width="302px"Height="50"runat="server"></asp:TextBox> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button ID="ButtonSpeak"runat="server"Text="发言"Width="72px"></asp:Button><asp:Button ID="ButtonExit"runat="server"Text="离开"Width="64px"Height="23px"></asp:Button><asp:DropDownList ID="DropDownListColor"runat="server"><asp:ListItem Value="black"Selected="True">黑色</asp:ListItem><asp:ListItem Value="red">红色</asp:ListItem><asp:ListItem Value="blue">蓝色</asp:ListItem><asp:ListItem Value="green">绿色</asp:ListItem></asp:DropDownList><asp:DropDownList ID="DropDownListEmotion"runat="server"><asp:ListItem Value="微笑着">微笑着</asp:ListItem><asp:ListItem Value="无奈地">无奈地</asp:ListItem><asp:ListItem Value="哭丧着脸">哭丧着脸</asp:ListItem> </asp:DropDownList></td></tr></table></form></body>后台:send.aspx.csusing System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.SqlClient;public partial class_Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}public DBConnection conn = new DBConnection();protected void ButtonSpeak_Click(object sender, EventArgs e){SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnStr"]);connection.Open();string createTime = System.DateTime.Now.ToString();//发言时间string content = TextBoxContent.Text; //发言内容string color = DropDownListColor.SelectedItem.Value; //颜色string emotion = DropDownListEmotion.SelectedItem.Value; //表情string sql;//SqlCommand cmd = new SqlCommand(sql, connection);//SqlDataReader dr = conn.ExecuteReader(sql);sql = "Insert into message(username,createtime,content1,color,emotion) values('"+ Session["username"]+ "','" + createTime+ "','" +content + "','" + color + "','" + emotion + "')";conn.Updata(sql);TextBoxContent.Text="";}protected void ButtonExit_Click(object sender, EventArgs e){Session["username"] = null;Response.Redirect("re.aspx");}}截图:--------------------------------------------------------------------------------------------------------------------------------------------------说明:这里因为要用到数据库sql 所以在开头加上命名空间:using System.Data.SqlClient;还有链接数据库的web.config 文件Web 。

聊天室程序代码---服务器端

聊天室程序代码---服务器端
int new_fd=client->sockfd;
int len;
char buf[MAXBUF + 1];
fd_set rfds;
struct timeval tv;
int retval, maxfd = -1;
while (1)
{
FD_ZERO(&rfds);
FD_SET(0, &rfds);
聊天室程序代码服务器端服务器端服务器源代码聊天室聊天程序服务端
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
{
perror("bind");
exit(1);
}
if (listen(*sockfd, lisnum) == -1)
{
perror("listen");
exit(1);
}
}
void *pthread_proc(void *arg)
{
SERVER_t *client=(SERVER_t *)arg;
return NULL;
if(*count==0&&head==NULL)
{
(*count)++;
head=p;
p->next=NULL;
return head;
}
else if(*count>0 && head != NULL)

C语言实现简易网络聊天室

C语言实现简易网络聊天室

C语⾔实现简易⽹络聊天室本⽂实例为⼤家分享了C语⾔实现⽹络聊天室的具体代码,供⼤家参考,具体内容如下业务逻辑:1、客户端注册名字2、告诉所有在线的客户端,XXX进⼊聊天室3、新建⼀个线程为该客户端服务,随时接收客户端发送来的消息4、当接收到⼀个客户端的消息时,向每⼀个客户端转发⼀份(群聊)5、同时在线⼈数最多50⼈任何客户端可以随意随时进⼊或退出客户端服务端代码server.c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <signal.h>#include <pthread.h>#include <semaphore.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#ifndef DEBUG#define debug(format,...) {}#else#define debug(format,...) \{\fprintf(stdout,"%s:%d:%s ",__func__,__LINE__,__TIME__);\fprintf(stdout,format,##__VA_ARGS__);\fprintf(stdout,"\n");\}#endif//DEBUG#define error(format,...)\{\fprintf(stdout,"%s:%d:%s ",__func__,__LINE__,__TIME__);\fprintf(stdout,format,##__VA_ARGS__);\fprintf(stdout,":%m\n");\exit(EXIT_FAILURE);\}// 客户端最⼤连接数#define CLIENT_MAX 50// 服务器端⼝号#define PORT 5566// 缓冲区⼤⼩#define BUF_SIZE 4096// 重定义socket地址类型typedef struct sockaddr* SP;// 客户端结构体typedef struct Client{int sock;//socket 标识符pthread_t tid; //线程IDchar name[20];struct sockaddr_in addr;}Client;// 定义50个存储客户端的结构变量Client clients[50];// 定义信号量⽤于限制客户端的数量sem_t sem;// 信号处理函数void sigint(int num){for(int i=0; i<10; i++){if(clients[i].sock){pthread_cancel(clients[i].tid);//销毁线程}}debug("服务器退出!");exit(EXIT_SUCCESS);}void client_eixt(Client* client){sem_post(&sem);close(client->sock);client->sock = 0;}void client_send(Client* client,char* buf){size_t len = strlen(buf)+1;for(int i=0; i<CLIENT_MAX; i++){if(clients[i].sock && clients[i].sock != client->sock) {send(clients[i].sock,buf,len,0);}}}void* run(void* arg){Client* client = arg;char buf[BUF_SIZE] = {};// 接收昵称int ret_size = recv(client->sock,client->name,20,0); if(0 >= ret_size){client_eixt(client);return NULL;}// 通知其它客户端新⼈上线sprintf(buf,"欢迎%s进⼊聊天室",client->name); client_send(client,buf);for(;;){// 接收消息ret_size = recv(client->sock,buf,BUF_SIZE,0);if(0 >= ret_size || 0 == strcmp("quit",buf)){// 通知其它客户端退出sprintf(buf,"%s退出聊天室",client->name);client_send(client,buf);client_eixt(client);return NULL;}strcat(buf,":");strcat(buf,client->name);client_send(client,buf);debug(buf);}}int main(int argc,const char* argv[]){signal(SIGINT,sigint);debug("注册信号处理函数成功!");sem_init(&sem,0,CLIENT_MAX);debug("初始化信号量成功!");int svr_sock = socket(AF_INET,SOCK_STREAM,0);if(0 > svr_sock){error("socket");}debug("创建socket对象成功!");struct sockaddr_in svr_addr = {};svr_addr.sin_family = AF_INET;svr_addr.sin_port = htons(PORT);svr_addr.sin_addr.s_addr = INADDR_ANY;socklen_t addrlen = sizeof(svr_addr);debug("准备通信地址成功!");if(bind(svr_sock,(SP)&svr_addr,addrlen)){error("bind");}debug("绑定socket对象和通信地址成功!");if(listen(svr_sock,10)){error("listen");}debug("设置监听socket监听成功!");for(;;){debug("等待客户端连接...");sem_wait(&sem);int index = 0;while(clients[index].sock){index++;}clients[index].sock = accept(svr_sock,(SP)&clients[index].addr,&addrlen);if(0 > clients[index].sock){kill(getpid(),SIGINT);}debug("有新的客户端连接,from ip:%s",inet_ntoa(clients[index].addr.sin_addr)); pthread_create(&clients[index].tid,NULL,run,&clients[index]);}}客户端代码client.c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <signal.h>#include <pthread.h>#include <semaphore.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#ifndef DEBUG#define debug(format,...) {}#else#define debug(format,...) \{\fprintf(stdout,"%s:%d:%s ",__func__,__LINE__,__TIME__);\fprintf(stdout,format,##__VA_ARGS__);\fprintf(stdout,"\n");\}#endif//DEBUG#define error(format,...)\{\fprintf(stdout,"%s:%d:%s ",__func__,__LINE__,__TIME__);\fprintf(stdout,format,##__VA_ARGS__);\fprintf(stdout,":%m\n");\exit(EXIT_FAILURE);\}#define BUF_SIZE 4096#define SERVER_PORT 5566#define SERVER_IP "192.168.0.125"typedef struct sockaddr* SP;void* run(void* arg){int cli_sock = *(int*)arg;char buf[BUF_SIZE] = {};for(;;){int ret_size = recv(cli_sock,buf,BUF_SIZE,0);if(0 >= ret_size){printf("服务器正在升级,请稍候登录!\n");exit(EXIT_SUCCESS);}printf("\r%30s\n>>>",buf);fflush(stdout);}}int main(int argc,const char* argv[]){int cli_sock = socket(AF_INET,SOCK_STREAM,0);if(0 > cli_sock){error("socket");}struct sockaddr_in cli_addr = {};cli_addr.sin_family = AF_INET;cli_addr.sin_port = htons(SERVER_PORT);cli_addr.sin_addr.s_addr = inet_addr(SERVER_IP);socklen_t addrlen = sizeof(cli_addr);if(connect(cli_sock,(SP)&cli_addr,addrlen)){printf("服务器正在升级,请稍候登录!\n");return EXIT_SUCCESS;}char buf[BUF_SIZE] = {};printf("请输⼊你的眤称:");gets(buf);send(cli_sock,buf,strlen(buf)+1,0);pthread_t tid;pthread_create(&tid,NULL,run,&cli_sock);for(;;){printf(">>>");gets(buf);send(cli_sock,buf,strlen(buf)+1,0);if(0 == strcmp("quit",buf)){printf("退出聊天室!\n");return EXIT_SUCCESS;}}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

编写程序实现一个简单的聊天室

编写程序实现一个简单的聊天室

1、编写程序实现一个简单的聊天室,要能显示发言人姓名、发言内容、发言人IP地址和发言时间。

(1)<html><frameset rows="*,60"><frame name="message" src="4.3.asp"><frame name="say" src="4.2.asp" ></frameset></html>(2)<html><body><form name="form1" method="post" action="">昵称:<input type="text" name="txtname" size="10" />发言:<input type="text" name="txtsay" size="50" /><input type="submit" value="发送" /></form><%if trim(request.Form("txtname "))<>""and trim(request.Form("txtsay"))<>"" then dim strsaystrsay=request.Form("txtname")&"说:"&request.Form("txtsay")&"<br>"application.Lockapplication("strchat")=strsay & application("strchat")application.UnLockend if%></body></html>(3) <html><head><title>显示发言页面</title><meta http-equiv="refresh" content="5" /></head><body><%response.Write application("strchat")%></body></html>2、开发一个简单的在线考试程序,包括5道单选题和5到多选题,单击“交卷”按钮后就可以根据标准答案在线评分。

java聊天室部分主要代码

java聊天室部分主要代码

ChatClient.javaimport java.awt.*;import java.io.*;import .*;import java.applet.*;import java.util.Hashtable;public class ChatClient extends Applet implements Runnable{ Socket socket=null;DataInputStream in=null;//读取服务器端发来的消息DataOutputStream out=null;//向服务器端发送的消息InputInfo 用户名提交界面=null;UserChat 聊天界面=null;Hashtable listTable;//用于存放在线用户的用户名的散列表Label 提示条;Panel north,center;Thread thread;public void init(){setSize(1000,800);int width=getSize().width;int height=getSize().height;listTable=new Hashtable();setLayout(new BorderLayout());用户名提交界面=new InputInfo(listTable);int h=用户名提交界面.getSize().height;聊天界面=new UserChat("",listTable,width,height-(h+5));聊天界面.setVisible(false);提示条=new Label("正在连接到服务器...",Label.CENTER);提示条.setForeground(Color.red);north=new Panel(new FlowLayout(FlowLayout.LEFT));center=new Panel();north.add(用户名提交界面);north.add(提示条);center.add(聊天界面);add(north,BorderLayout.NORTH);add(center,BorderLayout.CENTER);validate();}public void start(){if(socket!=null&&in!=null&&out!=null){try{socket.close();in.close();out.close();聊天界面.setVisible(false);}catch(Exception ee){}}try{socket=new Socket(this.getCodeBase().getHost(),6666);in=new DataInputStream(socket.getInputStream());out=new DataOutputStream(socket.getOutputStream());}catch(IOException ee){提示条.setText("连接失败");}//客户端成功连接服务器端if(socket!=null){InetAddress address=socket.getInetAddress();提示条.setText("连接:"+address+"成功");用户名提交界面.setSocketConnection(socket,in,out);north.validate();}if(thread==null){thread=new Thread(this);thread.start();}}public void stop(){try{socket.close();thread=null;}catch(IOException e){this.showStatus(e.toString());}}public void run(){while(thread!=null){if(用户名提交界面.getchatornot()==true){聊天界面.setVisible(true);聊天界面.setName(用户名提交界面.getName());聊天界面.setSocketConnection(socket,in,out);提示条.setText("祝聊天快乐!");center.validate();break;}try{Thread.sleep(100);}catch(Exception e){}}}}ChatMain.javaimport .*;import java.util.*;public class ChatMain {public static void main(String args[]) {ServerSocket server=null;Socket you=null;Hashtable peopleList;peopleList=new Hashtable();while(true){try{//服务器端在端口6666处监听来自客户端的信息server=new ServerSocket(6666);}catch(IOException e1){System.out.println("正在监听");}try{//当服务器端接收到客户端的消息后,取得客户端的IP地址。

java聊天程序代码

java聊天程序代码

import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;public class ChatJFrame extends JFrame implements ActionListener {private JTextArea text_receiver; //显示对话内容的文本区private JTextField text_sender; //输入发送内容的文本行private PrintWriter cout; //字符输出流对象private String name; //网名public ChatJFrame(String name, String title, PrintWriter cout) //构造方法{super("聊天室"+name+" "+title);this.setSize(320,240);this.setLocation(300,240);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.text_receiver = new JTextArea();this.text_receiver.setEditable(false); //不可编辑this.add(this.text_receiver);JPanel panel = new JPanel();this.add(panel,"South");this.text_sender = new JTextField(12);panel.add(this.text_sender);this.text_sender.addActionListener(this); //注册单击事件监听器JButton button_send = new JButton("发送");panel.add(button_send);button_send.addActionListener(this);JButton button_leave = new JButton("离线");panel.add(button_leave);button_leave.addActionListener(this);this.setVisible(true);this.setWriter(cout); = name;}public ChatJFrame(){this("","",null);}public void setWriter(PrintWriter cout) //设置字符输出流对象{this.cout = cout;}public void receive(String message) //显示对方发来的内容{text_receiver.append(message+"\r\n");}public void actionPerformed(ActionEvent e){if (e.getActionCommand()=="离线"){if (this.cout!=null){this.cout.println(name+"离线");this.cout.println("bye");this.cout = null;}text_receiver.append("我离线\n");}else //发送{if (this.cout!=null){this.cout.println(name+" 说:"+text_sender.getText());text_receiver.append("我说:"+text_sender.getText()+"\n"); text_sender.setText("");}elsetext_receiver.append("已离线,不能再发送。

java实现聊天室功能(包含全部代码-有界面)

java实现聊天室功能(包含全部代码-有界面)

服务器端代码:import .*;import .*;import .*;import .*;public class Server{private static final int PORT=6666;G_Menu gm=new G_Menu();private ServerSocket server;public ArrayList<PrintWriter> list;public static String user;public static ArrayList<User> list1=new ArrayList<User>();....");while(true){Socket client=();etServer();}class Chat implements Runnable{Socket socket;private BufferedReader br;private String msg;private String mssg="";public Chat(Socket socket){try{=socket;}catch(Exception ex){();}}public void run(){try{br=new BufferedReader(new InputStreamReader()));while((msg=())!=null){if("1008611"))plit(":");quals()+"("+()+")"))etOutputStream());quals ()))etOutputStream());quals(si[0]))lose();;import .*;import .*;import class Socket_one;import .*;import .*;import Landen extends Frame implements ActionListener {JFrame jf=new JFrame("聊天登陆");JPanel jp1=new JPanel();JPanel jp2=new JPanel();JPanel jp3=new JPanel();JPanel jp4=new JPanel();JLabel jl1=new JLabel("姓名:");JLabel jl2=new JLabel("地址:");JLabel jl3=new JLabel("端口:");JRadioButton jrb1=new JRadioButton("男生"); JRadioButton jrb2=new JRadioButton("女生"); JRadioButton jrb3=new JRadioButton("保密");public JTextField jtf1=new JTextField(10);public JTextField jtf2=new JTextField(10);public JTextField jtf3=new JTextField(10);JButton jb1=new JButton("连接");JButton jb2=new JButton("断开");TitledBorder tb=new TitledBorder("");ButtonGroup gb=new ButtonGroup();public void init()quals("断开")){(0);}if().equals("连接")){if().equals("")){(null,"请输入用户名!");}else if(!()&&!()&&!()){(null,"请选择性别!");}else{(false);if()){s1="boy";}else if()){s1="girl";}else if()){s1="secret";}G_Menu gmu=new G_Menu();(),s1);();}}}}public class Login{public static void main(String[] args) {new Landen().init();}}主界面代码:import .*;import .*;import .*;import .*;class G_Menu extends JFrame implements ActionListener {JFrame jf=new JFrame("聊天室");public Socket_one soc;public PrintWriter pw;public JPanel jp1=new JPanel();public JPanel jp2=new JPanel();public JPanel jp3=new JPanel();public JPanel jp4=new JPanel();public JPanel jp5=new JPanel();public JPanel jp6=new JPanel();public JPanel jp7=new JPanel();public static JTextArea jta1=new JTextArea(12,42); public static JTextArea jta2=new JTextArea(12,42);public JLabel jl1=new JLabel("对");public static JComboBox jcomb=new JComboBox();public JCheckBox jcb=new JCheckBox("私聊");public JTextField jtf=new JTextField(36);public JButton jb1=new JButton("发送>>");public JButton jb2=new JButton("刷新");public static DefaultListModel listModel1;public static JList lst1;public String na;public String se;public String message;public void getMenu(String name,String sex)quals("发送>>"))quals("")) {if()){String name1=(String)();message="悄悄话"+na+"("+se+")"+"对"+name1+"说:"+();("4");quals("刷新"));import .*;import .*;class User{private String name;//用户姓名private String sex;//用户性别private Socket sock;//用户自己的socketpublic User(String name,String sex,Socket sock){setName(name);setSex(sex);setSock(sock);}public String getName(){return name;}public void setName(String name){=name;}public String getSex(){return sex;}public void setSex(String sex){=sex;}public Socket getSock(){return sock;}public void setSock(Socket sock){=sock;}}使用说明:1、先将所有的类都编译一下2、先运行服务器端代码3、再运行登录界面代码。

网络编程作业聊天室代码

网络编程作业聊天室代码
public void run() {
while(! serverSocket.isClosed()) {
try {
Socket socket = serverSocket.accept(); //不停的接收请求
}
}
public static void main(String[] args) {
new ChatServer();
}
public void removeClient(ChatThread client) {
package name.zrl;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import .ServerSocket;
import .Socket;
import java.util.ArrayList;
import java.ut javax.swing.JButton;
break;
}
}
}
}).start();
}
}
public void sendMessage(String msg) {
for(ChatThread client : clients) {
client.sendMessage(msg);
JButton jbStart = new JButton("启动服务器");
JLabel jl = new JLabel("服务器的监听端口为8000");
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

聊天室客户端主要代码CSocket.hclass CChat_ClientDlg; //dlg类声明class CCSocket : public CSocket{DECLARE_DYNAMIC(CCSocket); //动态类声明public:CCSocket(CChat_ClientDlg* pDlg); //添加构造函数的入口函数virtual ~CCSocket();CChat_ClientDlg* m_pDlg;//指向对话框的指针变量。

virtual void OnReceive(int nErrorCode); //CSocket类添加的事件响应函数};CSokcet.cpp#include"stdafx.h"#include"Chat_Client.h"#include"CSocket.h"#include"Chat_ClientDlg.h" //自行添加的头文件,调用到dlg类的成员函数。

IMPLEMENT_DYNAMIC(CCSocket,CSocket) //动态类声明// CCSocket构造函数、析构函数CCSocket::CCSocket(CChat_ClientDlg* pDlg){m_pDlg=pDlg; //初始化对话框指针变量}CCSocket::~CCSocket(){m_pDlg=NULL;}// CCSocket 成员函数void CCSocket::OnReceive(int nErrorCode){// TODO: 在此添加专用代码和/或调用基类CSocket::OnReceive(nErrorCode);if(nErrorCode==0) m_pDlg->OnReceive(); //调用对话框类的对应函数}CChat_ClientDlg.h#pragma once#include"afxwin.h"#include"Msg.h" //自行添加的包含头文件#include"CSocket.h" //自行添加的包含头文件class CCSocket; //自行添加的类声明// CChat_ClientDlg 对话框类构造函数、析构函数…………protected:HICON m_hIcon;// 生成的消息映射函数virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnBnClickedButtonConnect(); //按钮单击事件响应函数声明afx_msg void OnBnClickedButtonClose();afx_msg void OnBnClickedButtonSend();afx_msg void OnDestroy(); //对话框销毁事件响应函数声明DECLARE_MESSAGE_MAP()public:CString m_strSName; // 服务器名称CString m_strCName; // 客户名称//控件变量UINT m_nPort; // 端口号,即聊天室频道CButton m_btnConnect;CButton m_btnClose;CString m_strMsg;CButton m_btnSend;CListBox m_listMsg;CCSocket* m_pSocket; //套接字指针变量CSocketFile* m_pFile;CArchive* m_pArchiveIn; // 用于输入的CArchive对象指针CArchive* m_pArchiveOut; // 用于输出的CArchive对象指针//成员函数void OnReceive(void);void ReceiveMsg(void);void SendMsg(CString strText , bool st);};Chat_ClientDlg.cpp#include"stdafx.h"#include"Chat_Client.h"#include"Chat_ClientDlg.h"#include"Msg.h" //包含头文件#include"CSocket.h" //包含头文件…………//构造函数,初始化变量CChat_ClientDlg::CChat_ClientDlg(CWnd* pParent /*=NULL*/) : CDialog(CChat_ClientDlg::IDD, pParent), m_strSName(_T("")), m_strCName(_T("")), m_nPort(0), m_strMsg(_T("")){m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);//初始化自定义变量m_pSocket=NULL;m_pFile=NULL;m_pArchiveIn=NULL;m_pArchiveOut=NULL;}……BEGIN_MESSAGE_MAP(CChat_ClientDlg, CDialog)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()//}}AFX_MSG_MAPON_BN_CLICKED(IDC_BUTTON_CONNECT,&CChat_ClientDlg::OnBnClickedButtonConnect)ON_BN_CLICKED(IDC_BUTTON_CLOSE,&CChat_ClientDlg::OnBnClickedButtonClose)ON_BN_CLICKED(IDC_BUTTON_SEND,&CChat_ClientDlg::OnBnClickedButtonSend)ON_WM_DESTROY()END_MESSAGE_MAP()// CChat_ClientDlg 消息处理程序BOOL CChat_ClientDlg::OnInitDialog(){…………// TODO: 在此添加额外的初始化代码// 初始化文本框变量,更新对话框m_nPort=8000;m_strSName=_T("localhost");UpdateData(FALSE);return TRUE; // 除非将焦点设置到控件,否则返回TRUE }……void CChat_ClientDlg::OnBnClickedButtonConnect(){// TODO: 在此添加控件通知处理程序代码UpdateData(TRUE);m_pSocket=new CCSocket(this); //创建套接字if(!m_pSocket->Create()){delete m_pSocket; // 错误处理m_pSocket=NULL;AfxMessageBox(_T("套接字创建错误!"));return;}if(!m_pSocket->Connect(m_strSName,m_nPort)){delete m_pSocket; // 错误处理m_pSocket=NULL;AfxMessageBox(_T("无法连接服务器!"));return;}m_pFile=new CSocketFile(m_pSocket);m_pArchiveIn=new CArchive(m_pFile,CArchive::load);m_pArchiveOut=new CArchive(m_pFile,CArchive::store);//调用SendMsg函数,向服务器发送消息,表明该客户机进入聊天室CString strTemp;strTemp=m_strCName+_T("进入聊天室"); //发送的消息设为:“客户名”进入聊天室SendMsg(strTemp,FALSE); //m_bClose设为FALSEGetDlgItem(IDC_EDIT_MSG)->EnableWindow(TRUE);GetDlgItem(IDC_BUTTON_CLOSE)->EnableWindow(TRUE);GetDlgItem(IDC_BUTTON_SEND)->EnableWindow(TRUE);GetDlgItem(IDC_EDIT_CLIENTNAME)->EnableWindow(FALSE);GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(FALSE);GetDlgItem(IDC_EDIT_SERVNAME)->EnableWindow(FALSE);GetDlgItem(IDC_EDIT_SERVPORT)->EnableWindow(FALSE);}void CChat_ClientDlg::OnBnClickedButtonClose(){// TODO: 在此添加控件通知处理程序代码CString strTemp;strTemp=m_strCName+_T(":离开聊天室!");SendMsg(strTemp,TRUE); //m_bClose设为TRUE//释放资源delete m_pArchiveOut; //删除用于输出的CArchive对象m_pArchiveOut=NULL;delete m_pArchiveIn; //删除用于输入的CArchive对象m_pArchiveIn=NULL;delete m_pFile;m_pFile=NULL;m_pSocket->Close();delete m_pSocket;m_pSocket=NULL;//清空列表框while(m_listMsg.GetCount()!=0)m_listMsg.DeleteString(0);GetDlgItem(IDC_EDIT_MSG)->EnableWindow(FALSE);GetDlgItem(IDC_BUTTON_CLOSE)->EnableWindow(FALSE);GetDlgItem(IDC_BUTTON_SEND)->EnableWindow(FALSE);GetDlgItem(IDC_EDIT_CLIENTNAME)->EnableWindow(TRUE);GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(TRUE);GetDlgItem(IDC_EDIT_SERVNAME)->EnableWindow(TRUE);GetDlgItem(IDC_EDIT_SERVPORT)->EnableWindow(TRUE);}void CChat_ClientDlg::OnBnClickedButtonSend(){// TODO: 在此添加控件通知处理程序代码UpdateData(TRUE); //取用户数据if(!m_strMsg.IsEmpty()){this->SendMsg(m_strCName+_T(":")+m_strMsg,FALSE);m_strMsg=_T("");UpdateData(FALSE);}}void CChat_ClientDlg::OnDestroy() //窗口销毁事件响应函数{CDialog::OnDestroy();// TODO: 在此处添加消息处理程序代码if((m_pSocket!=NULL)&&(m_pFile!=NULL)&&(m_pArchiveOut!=NULL)) {//发送客户机离开聊天室的消息CMsg msg;CString strTemp;strTemp=m_strCName+_T("DDDD:离开聊天室!");this->SendMsg(strTemp,TRUE);}delete m_pArchiveOut; //删除用于输出的CArchive对象m_pArchiveOut=NULL;delete m_pArchiveIn; //删除用于输入的CArchive对象m_pArchiveIn=NULL;delete m_pFile;m_pFile=NULL;delete m_pSocket;m_pSocket=NULL;}//CCSocket套接字调用的函数void CChat_ClientDlg::OnReceive(void){do{ReceiveMsg();if(m_pSocket==NULL) return;}while(!m_pArchiveIn->IsBufferEmpty());}//实际接收数据的函数void CChat_ClientDlg::ReceiveMsg(void){CMsg msg;try{//调用消息对象xuliehua函数,接收消息msg.Serialize(*m_pArchiveIn);m_listMsg.AddString(msg.m_strBuf); //将接收到的消息显示在列表框if(msg.m_bClose==true){delete m_pArchiveOut; //删除用于输出的CArchive对象m_pArchiveOut=NULL;delete m_pArchiveIn; //删除用于输入的CArchive对象m_pArchiveIn=NULL;delete m_pFile;m_pFile=NULL;m_pSocket->Close();delete m_pSocket;m_pSocket=NULL;//清空列表框while(m_listMsg.GetCount()!=0)m_listMsg.DeleteString(0);GetDlgItem(IDC_EDIT_MSG)->EnableWindow(FALSE);GetDlgItem(IDC_BUTTON_CLOSE)->EnableWindow(FALSE);GetDlgItem(IDC_BUTTON_SEND)->EnableWindow(FALSE);GetDlgItem(IDC_EDIT_CLIENTNAME)->EnableWindow(TRUE);GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(TRUE);GetDlgItem(IDC_EDIT_SERVNAME)->EnableWindow(TRUE);GetDlgItem(IDC_EDIT_SERVPORT)->EnableWindow(TRUE);}}catch(CFileException& e) //错误处理{//显示处理服务器关闭的消息CString strTemp;strTemp=_T("服务器重置连接!连接关闭!");m_listMsg.AddString(strTemp);msg.m_bClose=TRUE;m_pArchiveOut->Abort();//删除相应对象delete m_pArchiveOut; //删除用于输出的CArchive对象m_pArchiveOut=NULL;delete m_pArchiveIn; //删除用于输入的CArchive对象m_pArchiveIn=NULL;delete m_pFile;m_pFile=NULL;m_pSocket->Close();delete m_pSocket;m_pSocket=NULL;}}//实际向服务器发送数据的函数void CChat_ClientDlg::SendMsg(CString strText , bool st) {if(m_pArchiveOut!=NULL){CMsg msg;//将要发送的信息本文赋值给消息对象的成员变量msg.m_strBuf=strText;msg.m_bClose=st;//调用消息对象的序列化函数,发送消息msg.Serialize(*m_pArchiveOut);//将CArchive对象中的数据强制存储到CSocketfile对象中。

相关文档
最新文档