C++实现Socket 实现猜数字小游戏
时间: 2023-07-14 14:13:40 浏览: 183
好的,下面是C++实现Socket实现猜数字小游戏的代码示例:
服务端代码:
```c++
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;
int main()
{
// 创建套接字
int listenFd = socket(AF_INET, SOCK_STREAM, 0);
if (listenFd == -1)
{
cerr << "Failed to create socket!" << endl;
return -1;
}
// 配置地址
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(8080);
// 绑定地址
if (bind(listenFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1)
{
cerr << "Failed to bind address!" << endl;
return -1;
}
// 监听端口
if (listen(listenFd, 5) == -1)
{
cerr << "Failed to listen on socket!" << endl;
return -1;
}
// 接受连接
struct sockaddr_in clientAddr;
socklen_t clientAddrSize = sizeof(clientAddr);
int connFd = accept(listenFd, (struct sockaddr *)&clientAddr, &clientAddrSize);
// 生成随机数
srand(time(NULL));
int number = rand() % 100 + 1;
while (true)
{
// 读取客户端的猜测
char buffer[1024];
int n = read(connFd, buffer, sizeof(buffer));
if (n == -1)
{
cerr << "Failed to read from socket!" << endl;
break;
}
// 处理客户端的猜测
int guess = stoi(buffer);
if (guess == number)
{
write(connFd, "Correct!", 10);
break;
}
else if (guess > number)
{
write(connFd, "Too large!", 11);
}
else
{
write(connFd, "Too small!", 11);
}
}
// 关闭连接
close(connFd);
close(listenFd);
return 0;
}
```
客户端代码:
```c++
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main()
{
// 创建套接字
int clientFd = socket(AF_INET, SOCK_STREAM, 0);
if (clientFd == -1)
{
cerr << "Failed to create socket!" << endl;
return -1;
}
// 配置地址
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(8080);
// 连接服务器
if (connect(clientFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1)
{
cerr << "Failed to connect to server!" << endl;
return -1;
}
while (true)
{
// 读取用户的输入
string input;
cout << "Please guess a number (1-100): ";
getline(cin, input);
// 发送猜测
if (write(clientFd, input.c_str(), input.size()) == -1)
{
cerr << "Failed to write to socket!" << endl;
break;
}
// 读取结果
char buffer[1024];
int n = read(clientFd, buffer, sizeof(buffer));
if (n == -1)
{
cerr << "Failed to read from socket!" << endl;
break;
}
// 处理结果
cout << buffer << endl;
if (string(buffer) == "Correct!")
{
break;
}
}
// 关闭连接
close(clientFd);
return 0;
}
```
运行以上两个程序后,就可以开始猜数字小游戏了。服务端会生成一个1-100之间的随机数,客户端需要输入一个数字进行猜测,服务端会返回猜测结果(太大、太小或正确),直到猜中为止。
阅读全文