日期:2014-05-16 浏览次数:20671 次
//============================================================================ // Name : send_to_self.cpp // Author : AngryPowman // Version : // Copyright : * // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <arpa/inet.h> #include <string.h> using namespace std; #define SOCKET_ERROR -1 const int MAX_LEN = 4096; int main() { try { int listen_fd_ = socket(AF_INET, SOCK_STREAM, 0); if (listen_fd_ == SOCKET_ERROR) { cout << "Create socket error." << endl; return false; } int val = 1; if (0 != setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) { cout << "setsocket error." << endl; } sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(12345); int bind_err = bind(listen_fd_, (const sockaddr*)&addr, sizeof(addr)); if (bind_err == SOCKET_ERROR) { cout << "bind failed." << endl; return false; } int listen_err = listen(listen_fd_, SOMAXCONN); if (listen_err == SOCKET_ERROR) { cout << "listen failed." << endl; return false; } while (true) { int fd_client_new = 0; sockaddr_in addr_client; unsigned int len = sizeof(addr_client); fd_client_new = accept(listen_fd_, (sockaddr*)&addr_client, &len); if (fd_client_new == SOCKET_ERROR) { cout << "accept failed." << endl; } else { cout << "accept : " << inet_ntoa(addr_client.sin_addr) << endl; //cout << "accept client:" << //向监听套接字发送消息 cout << "send" << endl; int fd_sd = send(listen_fd_, "12345", strlen("12345"), 0); cout << "test" << endl; cout << fd_sd << endl; } } } catch (...) { cout << "exception." << endl; } sleep(10000); return 0; }