-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
51 lines (42 loc) · 1.43 KB
/
client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(1234);
// 无需bind,connect会自动绑定一个没有使用的本地端口
int result_connect = connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (result_connect < 0) {
printf("** Connect server failed, return code is: %d\n", result_connect);
return 1;
}
int result_write, result_read;
char buffer[512];
while (1) {
memset(buffer, 0, sizeof(buffer));
printf(">> Type message you want to send to server: ");
scanf("%s", buffer);
// write
result_write = write(sock, buffer, sizeof(buffer)-1);
if (result_write < 0) {
printf("** Write to server failed, return code is: %d\n", result_write);
break;
}
// read
result_read = read(sock, buffer, sizeof(buffer));
if (result_read <= 0) {
printf("** Read from server failed, return code is: %d\n", result_read);
break;
}
printf("<< Read from server: %s\n", buffer);
}
close(sock);
return 0;
}