当前位置: 首页 >> 程序设计 >> 单线程并发服务器(select) 编程
 

单线程并发服务器(select) 编程

作者:      来源:http://blog.csdn.net/kiki113     发表时间:2007-04-30     浏览次数:      字号:    

服务器代码:
 #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通信示例(传送文件)"文章

编辑 webmaster

 
 
 
评论更多>>
 
 
发表
 
姓名: QQ:
性别: MSN:
E-mail: 主页:
评分: 1 2 3 4 5
评论内容:
验证码:
  
  • 请遵守《互联网电子公告服务管理规定》及中华人民共和国其他各项有关法律法规。
  • 严禁发表危害国家安全、损害国家利益、破坏民族团结、破坏国家宗教政策、破坏社会稳定、侮辱、诽谤、教唆、淫秽等内容的评论 。
  • 用户需对自己在使用本站服务过程中的行为承担法律责任(直接或间接导致的)。
  • 本站管理员有权保留或删除评论内容。
  • 评论内容只代表网友个人观点,与本网站立场无关。
  •