当前位置:编程学习 > 网站相关 >>

TCP_server

#include "common.h"
 
 
int main (int argc, char *argv[])
{
 int sock_fd,conn_fd;
 struct sockaddr_in server_addr,client_addr;
 socklen_t addrlen = ADDR_SIZE;
 int wc = -1,rc = -1;
 char buffer_r[BUFFER_SIZE],buffer_w[BUFFER_SIZE];
 int i = 1;
 
 sock_fd = socket(AF_INET,SOCK_STREAM,0);
 if(sock_fd == -1)
  Err_sys("Server socket:")
 
 bzero(&server_addr,ADDR_SIZE);
 server_addr.sin_family = AF_INET;
 server_addr.sin_port = htons(Server_port);
 server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
 
 setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,(void *)&i,sizeof(i));
 
 if(bind(sock_fd,(struct sockaddr *)&server_addr,addrlen) == -1)
  Err_sys("Server bind:")
 
 if(listen(sock_fd,2) == -1)
  Err_sys("Server listen:")
 conn_fd = accept(sock_fd,(struct sockaddr *)&client_addr,&addrlen);
 if(conn_fd == -1)
  Err_sys("Server accept:")
 
 else
  printf("++++++++++++Accept Success++++++++++++++\n");
  
 printf("Connect client [ip]:%s [port]:%d\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); 
 
 while(RUNNING)
 {
  memset(buffer_r,0,BUFFER_SIZE);
 
  rc =  recv(conn_fd,buffer_r,BUFFER_SIZE,0);
  if(rc <= 0)
   Err_sys("Server recv:")
  printf("[Server recv]:%s\n",buffer_r);
 
  memset(buffer_w,0,BUFFER_SIZE);
  printf("[Server send]:");
  fflush(stdout);
  fgets(buffer_w,BUFFER_SIZE,stdin);
  wc =  send(conn_fd,buffer_w,BUFFER_SIZE,0);
  if(wc <= 0)
   Err_sys("Server send:")
 } //while
 
 shutdown(conn_fd,SHUT_RDWR);
 close(sock_fd);
 
 return 0;
}
补充:综合编程 , 其他综合 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,