本文主要是介绍MFC基于windows套接字函数代码示范,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
源文件下载: MFC_TCP_Client_chat1.rar
关键代码:
void CMFC_TCP_Client_chat1Dlg::OnBnClickedButtonSend() //登录按钮
{// TODO: 在此添加控件通知处理程序代码//sockaddr_in serveraddr;CString strport;m_ServerIP.GetWindowTextA(m_IP);m_ServerPort.GetWindowText(strport);if (strport.IsEmpty() || m_IP.IsEmpty()){MessageBox("请设置服务器IP和端口号");return;}m_Port = atoi(strport); //字符转整数serveraddr.sin_family = AF_INET;serveraddr.sin_port = htons(m_Port);serveraddr.sin_addr.S_un.S_addr = inet_addr(m_IP);//inet_addr,字符串转IP
// serveraddr.sin_addr.S_un.S_addr = InetPton(m_IP);if(connect(m_SockClient,(sockaddr*)&serveraddr,sizeof(serveraddr))!=0)//if (connect(m_SockClient, (sockaddr*)&serveraddr, sizeof(serveraddr)) == NULL){MessageBox("连接失败");return;}elseMessageBox("连接成功");DWORD nError = GetLastError();WSAAsyncSelect(m_SockClient,m_hWnd, CM_RECEIVE, FD_READ);//WSAAsyncSelect(m_SocketClient,m_hWnd,1000,FD_READ);//::WSAAsyncSelect(m_SocketClient,this->m_hWnd,CM_RECEIVE,FD_READ);//WSAAsyncSelect(m_SocketClient,m_hWnd,WM_USER+1000,FD_READ);CString strname, info;m_NickName.GetWindowTextA(strname);info.Format("%s-------->%s", strname, "进入聊天室了");send(m_SockClient, info.GetBuffer(0), info.GetLength(), 0);//MessageBox("already send");m_MsgList2.AddString(info);}HRESULT CMFC_TCP_Client_chat1Dlg::ReceiveInfo(WPARAM wParam, LPARAM lParam)
{char buffer[1024];if (lParam == FD_READ){int num = recv(m_SockClient, buffer, 1024, 0);if (num == -1)return E_NOTIMPL;buffer[num] = 0;m_MsgList2.AddString(buffer);}return E_NOTIMPL;
}void CMFC_TCP_Client_chat1Dlg::OnBnClickedButton2() //发送按钮
{// TODO: 在此添加控件通知处理程序代码CString strData, name, info;m_NickName.GetWindowTextA(name);//m_SendData.GetWindowTextA(info);m_SendData.GetWindowTextA(strData);//if(!name.IsEmpty()&&!info.IsEmpty())if (!name.IsEmpty() && !strData.IsEmpty()){info.Format("%s说:%s", name, strData);send(m_SockClient, info.GetBuffer(0), info.GetLength(), 0);m_MsgList2.AddString(info);m_SendData.SetWindowText("");}else{MessageBox("未连接或未输入");}
}
初始化位置添加:
// TODO: 在此添加额外的初始化代码m_SockClient = socket(AF_INET,SOCK_STREAM,0);m_ServerIP.SetWindowTextA("127.0.0.1");m_ServerPort.SetWindowTextA("6666");//::WSAAsyncSelect(m_SockClient, this->m_hWnd, CM_RECEIVE, FD_READ);DWORD error = GetLastError();m_NickName.SetWindowText("txwtech");
BOOL CMFC_TCP_Client_chat1App::InitInstance()里面添加:
if (!AfxSocketInit()) //new added,初始化套接字
{
//AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
return FALSE;
}
stdafx.h中添加:
#include "afxsock.h"
源文件下载:
这篇关于MFC基于windows套接字函数代码示范的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!