First off, you should not be calling WSAStartup() and WSACleanup() on every send. Call them one time at program startup/exit instead.
Second, you are not doing any error handling whatsoever. Any one of those system calls could fail.
Also, you are sending a blank CString. You meant to use GetDlgItemText() instead of SetDlgItemText().
Now, that being said, to answer your question, the receive code will look similar to this sending code, except that it will need to:
- create the receiving socket before the message is sent, otherwise the message will get discarded by the OS.
bind() the receiving socket to port 3514 instead of 0
- use
recvfrom() instead of sendto()
For example:
// client
CFinalProjectKeithDlg::CFinalProjectKeithDlg()
{
WSAData data;
if (WSAStartup(MAKEWORD(2, 2), &data) != 0)
throw ...;
}
CFinalProjectKeithDlg::~CFinalProjectKeithDlg()
{
WSACleanup();
}
void CFinalProjectKeithDlg::OnBnClickedSend()
{
CString ChatMessage;
GetDlgItemText(IDC_EDIT_CHAT, ChatMessage);
const char* srcIP = "127.0.0.1";
const char* destIP = "127.0.0.1";
sockaddr_in local;
local.sin_family = AF_INET;
inet_pton(AF_INET, srcIP, &local.sin_addr);
local.sin_port = htons(0);
sockaddr_in dest;
dest.sin_family = AF_INET;
inet_pton(AF_INET, destIP, &dest.sin_addr);
dest.sin_port = htons(3514);
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
throw ...;
if (bind(s, (sockaddr*)&local, sizeof(local)) == SOCKET_ERROR) {
closesocket(s);
throw ...;
}
char *msg = ChatMessage;
if (sendto(s, msg, strlen(msg), 0, (sockaddr*)&dest, sizeof(dest)) == SOCKET_ERROR) {
closesocket(s);
throw ...;
}
closesocket(s);
}
// server
private:
SOCKET s;
CFinalProjectKeithDlg::CFinalProjectKeithDlg()
{
WSAData data;
if (WSAStartup(MAKEWORD(2, 2), &data) != 0)
throw ...;
const char* srcIP = "127.0.0.1";
sockaddr_in local;
local.sin_family = AF_INET;
inet_pton(AF_INET, srcIP, &local.sin_addr);
local.sin_port = htons(3514);
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET) {
WSACleanup();
throw ...;
}
if (bind(s, (sockaddr*)&local, sizeof(local)) == SOCKET_ERROR) {
closesocket(s);
WSACleanup();
throw ...;
}
}
CFinalProjectKeithDlg::~CFinalProjectKeithDlg()
{
closesocket(s);
WSACleanup();
}
void CFinalProjectKeithDlg::OnBnClickedRead()
{
sockaddr_in from;
int fromlen = sizeof(from);
char msg[65536] = {};
if (recvfrom(s, msg, sizeof(msg)-1, 0, (sockaddr*)&from, &fromlen) == SOCKET_ERROR)
throw ...;
SetDlgItemText(IDC_EDIT_CHAT, msg);
}