用的广播IP,所以校内网不用设置,直接在校内网随便找台电脑打开服务端,然后再随便找台电脑打开客户端,然后就可以做100以内的加法了。。。
说明:客户端输入“ready”,服务端会随机发送一条加法算式,客户端发送结果,如果回答正确就显示“Right!”,然后可以输入“ready”做下一道题,否则显示“Wrong!”,需重新输入结果,直到做对为止。。。
还想加点UI,看来要学习多线程了。。。
就是这么蛋疼。。。
客户端
#include<stdio.h> #include<winsock.h> #pragma comment (lib,"ws2_32.lib") int main() { char buffer[1025]; WSADATA data; WSAStartup(MAKEWORD(2,0), &data); SOCKET mySocket; struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(7464); server.sin_addr.s_addr = inet_addr("10.7.4.255"); mySocket = socket(AF_INET, SOCK_DGRAM, 0); int len = sizeof(server); while(scanf("%s", buffer) != EOF) { sendto(mySocket, buffer, sizeof(buffer), 0,(sockaddr*)&server, len); recvfrom(mySocket, buffer, sizeof(buffer), 0, (sockaddr *)&server, &len); printf("%s ", buffer); } closesocket(mySocket); WSACleanup(); return 0; }
服务端
#include <stdio.h> #include <winsock.h> #include <string.h> #include <time.h> #pragma comment (lib,"ws2_32.lib") int main() { WSADATA data; WSAStartup(MAKEWORD(2, 0), &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(7464); mySocket = socket(AF_INET, SOCK_DGRAM, 0); bind(mySocket, (sockaddr *)&local, sizeof(local)); char right[] = "Right!"; char wrong[] = "Wrong!"; char inputError[] = "Input Error!"; char answer[10]; char buffer[1025]; srand(time(NULL)); int len = sizeof(from); while(1) { recvfrom(mySocket, buffer, sizeof(buffer), 0, (sockaddr *)&from, &len); if(strcmp(buffer, "ready") == 0) { int x = rand() % 100; int y = rand() % 100; int z = x + y; sprintf(answer, "%d", z); sprintf(buffer, "%d + %d = ?", x, y); sendto(mySocket, buffer, sizeof(buffer), 0, (sockaddr *)&from, len); int ok = 0; while(!ok) { recvfrom(mySocket, buffer, sizeof(buffer), 0, (sockaddr *)&from, &len); if(strcmp(buffer, answer) == 0) { ok = 1; sendto(mySocket, right, sizeof(right), 0, (sockaddr *)&from, len); } else sendto(mySocket, wrong, sizeof(wrong), 0, (sockaddr *)&from, len); } } else sendto(mySocket, inputError, sizeof(inputError), 0, (sockaddr *)&from, len); } closesocket(mySocket); WSACleanup(); return 0; }