Ai
1 Star 0 Fork 0

杨谨徽/代码托管

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
tcpclient.c 2.12 KB
一键复制 编辑 原始数据 按行查看 历史
杨谨徽 提交于 2023-11-12 21:29 +08:00 . add tcpclient.c.
#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;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/SHIBATORI/code-hosting.git
git@gitee.com:SHIBATORI/code-hosting.git
SHIBATORI
code-hosting
代码托管
master

搜索帮助