我想创建一个可以作为服务运行的应用程序以及另一个可以与之通信的程序(在 c++ 中)。基本上我希望程序向服务发送消息,而服务只是将它们回显给程序
程序的示例输出将是这样的: 请输入您的消息:你好 接收来自服务器的响应:你好
我有一个非常简单的 UDP 客户端服务器程序来执行此操作 - 服务器回显客户端发送的消息。所以我的问题是我可以将服务器更改为服务并更改客户端以使其仍与服务通信吗?如果是这样,这是怎么做的?
我以前从未使用过代码来创建服务,所以如果有人可以链接任何很棒的教程
这是我要更改的程序:服务器
void InitWinsock()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKET socketS;
InitWinsock();
struct sockaddr_in local;
struct sockaddr_in from;
int fromlen = sizeof(from);
local.sin_family = AF_INET;
local.sin_port = htons(1234);
local.sin_addr.s_addr = INADDR_ANY;
socketS = socket(AF_INET,SOCK_DGRAM,0);
bind(socketS,(sockaddr*)&local,sizeof(local));
while (1)
{
char buffer[1024];
ZeroMemory(buffer, sizeof(buffer));
printf("Waiting...\n");
if (recvfrom(socketS,buffer,sizeof(buffer),0,(sockaddr*)&from,&fromlen)!=SOCKET_ERROR)
{
printf("Received message from %s: %s\n",inet_ntoa(from.sin_addr), buffer);
sendto(socketS, buffer, sizeof(buffer), 0, (sockaddr*)&from, fromlen);
}
Sleep(500);
}
closesocket(socketS);
return 0;
}
客户:
void InitWinsock()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKET socketC;
InitWinsock();
struct sockaddr_in serverInfo;
int len = sizeof(serverInfo);
serverInfo.sin_family = AF_INET;
serverInfo.sin_port = htons(1234);
serverInfo.sin_addr.s_addr = inet_addr("127.0.0.1");
socketC = socket(AF_INET,SOCK_DGRAM,0);
while (1)
{
char buffer[1024];
ZeroMemory(buffer, sizeof(buffer));
printf("Please input your message: ");
scanf("%s", buffer);
if (strcmp(buffer,"exit") == 0)
break;
if (sendto(socketC, buffer, sizeof(buffer), 0, (sockaddr*)&serverInfo, len) != SOCKET_ERROR)
{
if (recvfrom(socketC, buffer, sizeof(buffer), 0, (sockaddr*)&serverInfo, &len) != SOCKET_ERROR)
{
printf("Receive response from server: %s\n", buffer);
}
}
}
closesocket(socketC);
return 0;
}