加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server.cpp 1.76 KB
一键复制 编辑 原始数据 按行查看 历史
Hevake Lee 提交于 2015-03-14 08:20 . Add bind port message
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <strings.h>
using namespace std;
void signal_handler(int sig);
const char *host_ip = "127.0.0.1";
const int host_port = 7000;
bool b_is_running = true;
int main()
{
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
cerr << "create socket error" << endl;
return 1;
}
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(host_ip);
server_addr.sin_port = htons(7000);
if (bind(server_socket, (const struct sockaddr*)&server_addr,
sizeof(server_addr)) == -1) {
cerr << "bind error" << endl;
close(server_socket);
return 1;
}
cout << "binding at " << host_port << endl;
listen(server_socket, 10);
cout << "--Start--" << endl;
signal(SIGKILL, signal_handler);
struct sockaddr client_addr;
socklen_t client_addr_len;
int client_socket = accept(server_socket, &client_addr, &client_addr_len);
if (client_socket == -1) {
cerr << "accept error." << endl;
} else {
cout << "accept connect." << endl;
}
const int buffer_size = 1024;
char buffer[buffer_size] = {0};
while (b_is_running) {
bzero(buffer, buffer_size);
int rsize = recv(client_socket, buffer, buffer_size, 0);
cout << "recv: " << buffer;
send(client_socket, "Got it.\n", 8, 0);
}
close(client_socket);
close(server_socket);
cout << "--End--" << endl;
return 0;
}
void signal_handler(int sig)
{
b_is_running = false;
cout << "Ctrl+C" << endl;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化