socket通信 server端
程序员文章站
2022-04-24 13:27:35
...
socket通信 server端
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc,char *argv[])
{
if(argc < 2){
printf("./a.out port\n");
exit(1);
}
int port = atoi(argv[1]);
struct sockaddr_in serv;
int sfd = socket(AF_INET,SOCK_STREAM,0);
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port = htons(port);
serv.sin_family = AF_INET;
bind(sfd,(struct sockaddr *)&serv,sizeof(serv));
listen(sfd,500);
printf("Start accept...\n");
struct sockaddr_in client;
socklen_t cli_len = sizeof(client);
int cfd = accept(sfd,(struct sockaddr *)&client,&cli_len);
if(cfd == -1){
perror("accept err");
exit(1);
}
printf("客户端IP:%s,port:%d连接\n",\
inet_ntoa(client.sin_addr),\
ntohs(client.sin_port));
while(1){
char buf[1024];
memset(buf,0,sizeof(buf));
int len = recv(cfd,buf,sizeof(buf),0);
if(len == -1){
perror("recv err");
exit(1);
}
else if(len == 0){
printf("客户端IP:%s,port:%d断开了连接\n",\
inet_ntoa(client.sin_addr),\
ntohs(client.sin_port));
close(cfd);
break;
}
else{
printf("recv : ");
printf("%s\n",buf);
memset(buf,0,sizeof(buf));
printf("send : ");
fgets(buf,sizeof(buf),stdin);
send(cfd,buf,strlen(buf),0);
//printf("send : %s\n",buf);
}
}
close(sfd);
return 0;
}
上一篇: tcp socket通信例子
下一篇: java socket通信例子