mfc CSocket类
我要编写的是一个简单的网络程序,模拟聊天的,但只是为了实现一个客户端连接服务端,客户端向服务端发送信息,服务端再返回该消息的功能
客户端:
从CSocket中派生出CMySocket类
重载了函数
void CMySocket::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
CSampleclientDlg *m_pDlg=(CSampleclientDlg *)AfxGetMainWnd();
m_pDlg->DealReceive();
CSocket::OnReceive(nErrorCode);
}
其中定义了
void CSampleclientDlg::DealReceive()
{
char *buff=new char[1024];
m_socketClient.Receive(buff,1024,0);
m_listMessage.AddString(buff);
}
m_listMessage是一个列表控件的一个控制变量
发送到消息处理
void CSampleclientDlg::OnSend()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
char *buff=new char[1024];
buff=(LPSTR)(LPCTSTR)m_strMessage;
m_socketClient.Send(buff,1024,0);
m_strMessage="";
UpdateData(FALSE);
}这是一个发送按钮的消息处理,m_strMessage是文本编辑框的变量
当然还有在初始化中,即对话款初始(我是用做对话框为基础的程序)的加入套接字的初始
m_socketClient.Create(5051,SOCK_STREAM,NULL);
if(m_socketClient.Connect("127.0.0.1",5050))
{
}
else
AfxMessageBox("无法连接服务器");
客户端可以确定建立的没有问题,因为我用另一个用api直接写服务端的程序可以正常工作
以下是我建立服务端的过程,这样建立的服务端不知怎么的很奇怪,在编译完运行服务端,这时客户端可以连接并正常工作。
关闭服务程序,再运行,客户端就没法连接了。只有在重新编译服务端又可以再正常工作一次。关闭就又不行了
服务端程序主界面是对话框,主要是两个按钮,开始和停止
void CChatRoomServerDlg::OnStart()
{
// TODO: Add your control notification handler code here
GetDlgItem(IDC_START)->EnableWindow(FALSE);
m_socketListen.Create(5050,SOCK_STREAM,NULL);
m_socketListen.Listen(5);
GetDlgItem(IDC_STOP)->EnableWindow(TRUE);
}
void CChatRoomServerDlg::OnStop()
{
// TODO: Add your control notification handler code here
GetDlgItem(IDC_STOP)->EnableWindow(FALSE);
m_socketListen.Close();
m_socketClient.Close();
GetDlgItem(IDC_START)->EnableWindow(TRUE);
}
我是重CSocket中派生出CMySocket的
重载了
void CMySocket::OnAccept(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
CChatRoomServerDlg * m_pDlg=(CChatRoomServerDlg *)AfxGetMainWnd();
Accept(m_pDlg->m_socketClient);
CSocket::OnAccept(nErrorCode);
}
void CMySocket::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
CChatRoomServerDlg * m_pDlg=(CChatRoomServerDlg *)AfxGetMainWnd();
m_pDlg->DealMessage();
CSocket::OnReceive(nErrorCode);
}
定义
void CChatRoomServerDlg::DealMessage()
{
char buff[1024];
int count;
count=m_socketClient.Receive(buff,1024,0);
m_socketClient.Send(buff,1024,0);
}
我是新手,刚学win32 请指点下
我尝试把m_socketClient定义为动态的,有时候可以不用重新编译就可以让他正常工作