net-server/sss.c
macbook-pro c0eea479aa use ggg
2023-12-18 06:23:29 +08:00

74 lines
2.2 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <errno.h>
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
int server_sockfd; //服务端套接字
int client_sockfd; //客户端套接字
int len;
struct sockaddr_in my_add; //服务器网络地址结构体
struct sockaddr_in remote_addr; //客户端网络地址结构体
socklen_t sin_size;
char buf[BUFSIZ]; //数据传送的缓冲区
memset(&my_add,0,sizeof(my_add)); //数据初始化--清零
my_add.sin_family = AF_INET; //设置为IP通信
my_add.sin_addr.s_addr = INADDR_ANY; //服务器IP地址--允许连接到所有本地地址上
my_add.sin_port = htons(8000); //服务器端口号
//创建服务器端套接字--IPV4协议 面向连接通信TCP协议
if((server_sockfd=socket(PF_INET, SOCK_STREAM, 0))<0) {
perror("socket");
return 1;
}
//将套接字绑定到服务器的网络地址上
if (bind(server_sockfd, (struct sockaddr *)&my_add, sizeof(struct sockaddr))<0) {
perror("bind");
return 1;
}
//监听连接请求--监听队列长度为5
listen(server_sockfd, 5);
sin_size = sizeof(struct sockaddr_in);
//等待客户端连接请求到达
if ((client_sockfd=accept(server_sockfd, (struct sockaddr *)&remote_addr, &sin_size))<0) {
perror("accept");
return 1;
}
printf("accept client %s\n",inet_ntoa(remote_addr.sin_addr));
len = send(client_sockfd, "welcome to my server\n", 21, 0); //发送欢迎信息
//接受客户端的数据并将其发送给客户端--recv返回接收到的字节数send返回发送的字节数
while (1) {
memset(buf,0,sizeof(buf));
len = recv(client_sockfd, buf, BUFSIZ, 0);
send(client_sockfd,buf, len, 0);
buf[len]='\0';
printf("receive:%s\n",buf);
if(buf[0]=='q'){
send(client_sockfd,'q', 1, 0);
break;
}
}
close(client_sockfd);
close(server_sockfd);
return 0;
}