加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server-socket.cpp 1018 Bytes
一键复制 编辑 原始数据 按行查看 历史
Hevake Lee 提交于 2015-03-13 16:49 . First Commit
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
using namespace std;
int main()
{
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0) {
cerr << "Create socket error!";
}
const int port = 5000;
struct sockaddr_in s_addr;
bzero(&s_addr, sizeof(s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
s_addr.sin_port = htons(port);
if (bind(sfd, (struct sockaddr*)&s_addr, sizeof(s_addr)) < 0) {
cerr << "Bind error";
}
listen(sfd, 10);
struct sockaddr c_addr;
socklen_t len;
char buffer[1024];
int cfd = accept(sfd, &c_addr, &len);
while (true) {
bzero(buffer, 1024);
int rsize = recv(cfd, buffer, 1024, 0);
cout << "Read size: " << rsize << endl;
cout << "Content: " << buffer << endl;
send(cfd, "Got it\n", 6, 0);
}
close(cfd);
close(sfd);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化