代码拉取完成,页面将自动刷新
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h> // Added inclusion of arpa/inet.h for bzero function
#define MAX 256
#define SERVER_HOST "localhost"
#define SERVER_PORT 1234
struct sockaddr_in server_addr;
int sock, r;
int client_init() {
printf("================ client init =================\n");
// 1. Create a TCP socket
printf("1 : create a TCP socket\n");
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("socket call failed");
exit(1);
}
// 2. Fill server_addr with server's IP and PORT#
printf("2 : fill server_addr with server's IP and PORT#\n");
memset((char*)&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Use localhost
server_addr.sin_port = htons(SERVER_PORT);
// 3. Connect to server
printf("3 : connecting to server ...\n");
r = connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (r < 0) {
perror("connect failed");
exit(3);
}
printf("4 : connected OK to\n");
printf("-----------------------------\n");
printf("Server hostname=%s PORT=%d\n", SERVER_HOST, SERVER_PORT);
printf("-----------------------------\n");
printf("================ init done ================\n");
}
int main() {
int n;
char line[MAX], ans[MAX];
client_init();
printf("********** processing loop ************\n");
while (1) {
printf("input a line : ");
bzero(line, MAX); // Zero out line[]
fgets(line, MAX, stdin); // Get a line from stdin
line[strlen(line) - 1] = '\0'; // Kill \n at end
if (line[0] == '\0') // Exit if NULL line
exit(0);
// Send line to server
n = write(sock, line, MAX);
printf("client: wrote n=%d bytes; line=%s\n", n, line);
// Read a line from sock and show it
n = read(sock, ans, MAX);
printf("client: read n=%d bytes; echo=%s\n", n, ans);
}
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。