单线程并发服务器(select)

服务器代码:
 #include "creatSocket.h"
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
//#include "error.h"

#define BUFFSIZE 20
extern int errno;
main()
{
  int temp_sock;
  int ssock;
  char buff[BUFFSIZE+1];
 
  struct sockaddr_in pin;
  int size_pin = sizeof(pin);
  int count_receive ;       /* count the receive world */
  int fd;                   /* mark the file */
  int count;                /* count the number of reading */
 
  ssock = passiveTCP("8000",5);
  while(1)
  {
    printf("listen.../n");
    temp_sock = accept(ssock,(struct sockaddr *)&pin,&size_pin);
    count_receive = read(temp_sock,buff,BUFFSIZE);
    printf("has receive message:%s/n",buff);
   
    fd = open(buff,O_RDWR);
    if(fd < 0)
       errexit("can't open the file:%s/n",strerror(errno));
    while(count = read(fd,buff,BUFFSIZE))
    {
          buff[count] = '/0';
          printf("%s",buff);
          write(temp_sock,buff,count);
    }
    close(temp_sock);
    printf("the connect has closed!/n");
  }
}
客户端代码:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <netdb.h>
#include <string.h>
#include "error.h"

extern int errno;
#define BUFFSIZE 4096

int main(int argc,char *argv[])
{
  char buf[BUFFSIZE];
  int cc;
  int port = 7;
  struct sockaddr_in sin;
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = INADDR_ANY;
 
  switch(argc)
  {
    case 1:sin.sin_port = htons(port);break;
    case 2:
    {
      if((sin.sin_port = htons((unsigned short)atoi(argv[1]))) == 0)
        errexit("sin.sin_port:%s/n",strerror(errno));
      break;
    }
    default:errexit("the argument has wrong!/n");
  }
  int csock = socket(AF_INET,SOCK_STREAM,0);
  printf("the connect port is %d/n",sin.sin_port);
 
  if(connect(csock,(void *)&sin,sizeof(sin)))
    errexit("has't connect to the server!:%s/n",strerror(errno));
  else
    printf("has connect to the server!/n");
 
  while(1)
  {
    printf("please input the send message:");
    scanf("%s",buf);
    write(csock,buf,sizeof(buf)); 
    cc = read(csock,buf,sizeof(buf));
    printf("the receive message is :%s/n",buf);
    if(buf[0] == 'q')
       break;
 }
}
errexit()和passiveTCP()两个方法见"linux socket通信示例(传送文件)"文章
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值