Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
#include #include #include #include int main() { // open server socket int srv_sock; // server socket int cli_sock; // client socket int result = 0; struct sockaddr_in srv_addr; // local address struct sockaddr_in cli_addr; // remote address // Construct local addr structure srv_addr.sin_family = AF_INET; srv_addr.sin_addr.s_addr = htonl(INADDR_ANY); // accept on any interface srv_addr.sin_port = htons(7000); // construct socket srv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (srv_sock < 1) { printf("Failed to create server socket\n"); exit(1); } // bind result = bind(srv_sock, (struct sockaddr*) &srv_addr, sizeof(struct sockaddr_in)); if (result < 0) { printf("Failed to bind server to address and port\n"); exit(1); } // listen and enqueue at most 5 clients result = listen(srv_sock, 5); if (result < 0) { printf("Failed to start listening\n"); exit(1); } // for getting data int received_bytes = 0; char received_string[512]; while(1) { // accept a connection // WARNING: must initialize this length or accept() won't fill the address struct. unsigned int sock_addr_len = sizeof(struct sockaddr_in); cli_sock = accept(srv_sock, (struct sockaddr*)&cli_addr, &sock_addr_len); printf("Connected to client socket %d\n", cli_sock); printf(" len: %d\n", sock_addr_len); send(cli_sock, (const void *) "HELLO\n", 6, 0); printf(">>> Sent HELLO\n"); received_bytes = recv(cli_sock, (void *)received_string, 512, 0); received_string[received_bytes] = '\0'; printf("<<< Received: %s\n", received_string); if (strncmp("quit", received_string, 4) == 0) { printf("Quitting...\n"); break; } printf("Closing connection to client %s\n", inet_ntoa(cli_addr.sin_addr)); shutdown(cli_sock, SHUT_RDWR); close(cli_sock); } close(srv_sock); }