客户端
代码步骤
- 调用socket函数来创建一个IPV4(AF_INET)字节流(SOCK_STREAM)套接字,返回标识符
- 将服务器的IP地址和端口号填入sockaddr_t结构的变量中,地址族设定为AF_INET,IP地址和端口必须要是特地格式,使用htons转换端口,使用inet_pton转换IP地址
- 调用connet函数和指定的服务器建立一个TCP连接
- 使用read/write来与服务器通信
代码示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(int argc, char const *argv[]) {
int socketfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socketfd < 0) {
perror("socket create failed!\n");
return 0;
}
struct sockaddr_in c_addr;
memset(&c_addr, 0x00, sizeof(struct sockaddr_in));
c_addr.sin_family = AF_INET;
c_addr.sin_port = htons(6666);
inet_pton(AF_INET, "127.0.0.1", &c_addr.sin_addr);
int result = connect(socketfd, (struct sockaddr*)&c_addr, sizeof(struct sockaddr_in));
if (result < 0) {
perror("connect failed!\n");
return 0;
}
int size = 0;
char buffer[1024] = {"hello server, I'm client!"};
size = write(socketfd, buffer, strlen(buffer));
printf("send to server size: %d\n", size);
memset(buffer, 0x00, 1024);
while((size = read(socketfd, buffer, 1024)) > 0) {
printf("server say: %s\n", buffer);
memset(buffer, 0x00, 1024);
}
close(socketfd);
return 0;
}
服务端
代码步骤
- 调用socket函数来创建一个IPV4(AF_INET)字节流(SOCK_STREAM)套接字,返回标识符
- 将服务器的IP地址和端口号填入sockaddr_t结构的变量中,地址族设定为AF_INET,IP地址和端口必须要是特地格式,IP地址使用INADDR_ANY表示任意IP
- 调用bind函数绑定所创建的套接字
- 调用listen将套接字转换为监听套接字,这样外来连接可以通过该套接字被内核接受
- 调用accept,服务器进入睡眠状态,等待客户的连接,完成3次握手,然后返回一个握手成功的描述符,新描述符用于与客户端通讯
- 使用read/write与客户端通讯
- 调用close来关闭与客户端的连接
代码示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(int argc, char const *argv[]) {
int socketfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socketfd < 0) {
perror("socket create failed!\n");
return 0;
}
struct sockaddr_in s_addr;
memset(&s_addr, 0x00, sizeof(struct sockaddr_in));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(6666);
s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(socketfd, (struct sockaddr*)&s_addr, sizeof(struct sockaddr));
listen(socketfd, 10);
while (true) {
int accsocfd = accept(socketfd, NULL, NULL);
int size = 0;
char buffer[1024] = {0};
size = read(accsocfd, buffer, 1024);
printf("client say: %s\n", buffer);
memset(buffer, 0x00, 1024);
snprintf(buffer, 1024, "%s", "I'm server, I received your message!");
size = write(accsocfd, buffer, strlen(buffer));
printf("send to client size: %d\n", size);
close(accsocfd);
}
close(socketfd);
return 0;
}
|