网站制作学习网Linux→正文:C socket 通信客户端
字体:

C socket 通信客户端

Linux 2012/9/18 18:30:51  点击:不统计


根据网上的改了改,写了个简单的socket通信,具有相当大的bug,是需要在修改的。
基本实现是从客户端链接,然后发送数据,服务器接收数据并返回发送的内容。
这里的服务器端,有一个很大的bug(也不算),是每个clint都有一个新的process,嘿嘿,需要修改滴
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define SERVPORT 3333
#define BACKLOG 10
#define MAXSIZE 1024

int main(){
  int sockfd,client_fd;
  struct sockaddr_in my_addr;
  struct sockaddr_in remote_addr;
//create socket
  if((sockfd = socket(AF_INET,SOCK_STREAM,0))== -1){
      perror("socket creat failed!");
      exit(1);
  }
 //bind port
 my_addr.sin_family = AF_INET;
 my_addr.sin_port   = htons(SERVPORT);
 my_addr.sin_addr.s_addr = INADDR_ANY;
 bzero(&(my_addr.sin_zero),8);
 if(bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr))== -1){
   perror("bind error!1");
   exit(1);
 }
 //keep listen
 if(listen(sockfd,BACKLOG) == -1){
   perror("listen error");
   exit(1);
  }
 while(1){
   int sin_size = sizeof(struct sockaddr_in);
   client_fd = accept(sockfd,(struct sockaddr *)&remote_addr,&sin_size);
   if(client_fd == -1){
    perror("accept error!");
    continue;
  }
 //printf("Receivd a connection from %s\n",(char*)inet_ntoa(remote_addr.sin_addr));
 //child precess
 if(!fork()){
   //accept client send message
   int rval;
   char buf[MAXSIZE];
cc:
   memset(buf,'\0',MAXSIZE); 
   if((rval = read(client_fd,buf,MAXSIZE))<0){
    perror("read stream error!");
    continue;
   }
   printf("%s\n",buf);   
   char* msg = "Hello world!";
   if(send(client_fd,msg,strlen(msg),0)== -1){
    perror("send error");
    close(client_fd);
    exit(0);
   }
   goto cc;
   close(client_fd);
 }
 //return 0;
  continue;
 }
 return 0;
}

 


·上一篇:linux c编程注意的几点 >>    ·下一篇:C socket 通信服务端端 >>
推荐文章
最新文章