所以我正在尝试创建一个迷你聊天应用程序,只是为了进入并理解套接字编程和关于线程的一两件事,我正在使用 c++ Mfc 进行操作,我可以在客户端和服务器之间建立连接(已验证它与netstat)但至于send和recv函数,我不太明白它应该如何完成,我从客户端应用程序发送一条消息,但服务器似乎没有收到它
服务器源代码:
int RcvThread();
SOCKET s;
void CChat_ServerDlg::OnBnClickedButton2()
{
WSADATA w;
int error = WSAStartup ( 0x0202,&w);
if(error)
{
OnCancel();
}
if (w.wVersion != 0x0202)
{
WSACleanup ();
OnCancel();
}
SOCKADDR_IN addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(DEFAULT_PORT);
addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
s = socket ( AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
OnCancel();
}
if (bind(s, (LPSOCKADDR)&addr, sizeof(addr)) == SOCKET_ERROR)
{
OnCancel();
}
listen (s, SOMAXCONN);
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE) RcvThread, NULL, NULL, NULL);
int buffsize = 1024;
char msg[1024] = "a";
int marker;
}
int RcvThread()
{
char sbuffer[256];
char buffer[sizeof(sbuffer)] = {0};
for(;; )
{
if(recv(s, buffer, sizeof(sbuffer), NULL) > 0)
{
memcpy(&sbuffer, buffer, sizeof(sbuffer));
MessageBox(hnd,sbuffer,"message",NULL);
}
}
return 0;
}
客户源代码:
SOCKET s;
void CChat_ClientDlg::OnBnClickedOk()
{
WSADATA wsadata;
int error = WSAStartup(0x0202,&wsadata);
if (error)
{
MessageBox("Error","ERRR");
OnCancel();
}
if (wsadata.wVersion != 0x0202)
{
WSACleanup ();
OnCancel();
}
SOCKADDR_IN target;
target.sin_family = AF_INET;
target.sin_port = htons(3124);
target.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
s = socket ( AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
OnCancel();
}
if (connect(s, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
{
OnCancel();
}
}
按钮发送消息:
void CChat_ClientDlg::OnBnClickedButton2()
{
char* Msg = new char[256];
Msg = "abdouabdouabdou";
send(s,Msg,256,NULL);
}