无聊拿socket写的100以内的加法考试。。。

时间:2024-10-03 21:07:26

用的广播IP,所以校内网不用设置,直接在校内网随便找台电脑打开服务端,然后再随便找台电脑打开客户端,然后就可以做100以内的加法了。。。

说明:客户端输入“ready”,服务端会随机发送一条加法算式,客户端发送结果,如果回答正确就显示“Right!”,然后可以输入“ready”做下一道题,否则显示“Wrong!”,需重新输入结果,直到做对为止。。。

还想加点UI,看来要学习多线程了。。。

就是这么蛋疼。。。

客户端

#include<stdio.h>
#include<winsock.h>
#pragma comment (lib,"ws2_32.lib") int main()
{
char buffer[];
WSADATA data;
WSAStartup(MAKEWORD(,), &data);
SOCKET mySocket;
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons();
server.sin_addr.s_addr = inet_addr("10.7.4.255");
mySocket = socket(AF_INET, SOCK_DGRAM, );
int len = sizeof(server);
while(scanf("%s", buffer) != EOF)
{
sendto(mySocket, buffer, sizeof(buffer), ,(sockaddr*)&server, len);
recvfrom(mySocket, buffer, sizeof(buffer), , (sockaddr *)&server, &len);
printf("%s\n", buffer);
}
closesocket(mySocket);
WSACleanup();
return ;
}

服务端

#include <stdio.h>
#include <winsock.h>
#include <string.h>
#include <time.h>
#pragma comment (lib,"ws2_32.lib") int main()
{
WSADATA data;
WSAStartup(MAKEWORD(, ), &data);
SOCKET mySocket;
sockaddr_in from;
sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
local.sin_port = htons();
mySocket = socket(AF_INET, SOCK_DGRAM, );
bind(mySocket, (sockaddr *)&local, sizeof(local));
char right[] = "Right!";
char wrong[] = "Wrong!";
char inputError[] = "Input Error!";
char answer[];
char buffer[];
srand(time(NULL));
int len = sizeof(from);
while()
{
recvfrom(mySocket, buffer, sizeof(buffer), , (sockaddr *)&from, &len);
if(strcmp(buffer, "ready") == )
{
int x = rand() % ;
int y = rand() % ;
int z = x + y;
sprintf(answer, "%d", z);
sprintf(buffer, "%d + %d = ?", x, y);
sendto(mySocket, buffer, sizeof(buffer), , (sockaddr *)&from, len);
int ok = ;
while(!ok)
{
recvfrom(mySocket, buffer, sizeof(buffer), , (sockaddr *)&from, &len);
if(strcmp(buffer, answer) == )
{
ok = ;
sendto(mySocket, right, sizeof(right), , (sockaddr *)&from, len);
}
else
sendto(mySocket, wrong, sizeof(wrong), , (sockaddr *)&from, len);
}
}
else sendto(mySocket, inputError, sizeof(inputError), , (sockaddr *)&from, len);
}
closesocket(mySocket);
WSACleanup();
return ;
}