Chinaunix首页 | 论坛 | 博客
  • 博客访问: 891967
  • 博文数量: 299
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2493
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-21 10:07
个人简介

Linux后台服务器编程。

文章分类

全部博文(299)

文章存档

2015年(2)

2014年(297)

分类: 网络与安全

2014-10-25 16:23:02

服务器的创建分为两个步骤:
1、建立socket;
2、创建线程。

两点内容的细节:
1、建立socket方面:
socket()
bind()
listen()
accept()

read()
write()

close()//关闭套接字时候在线程中关闭,而且只需关闭一次,在父进程中无须关闭socket,这一点不同于fork创建的进程。
相关的套接字API如上所示。


2、创建线程方面:
线程处理函数:
void* worker(void* arg);
pthread_create();
需要注意参数传递时要格式化成为void*的形式。
线程使用的tid方面,可以使用同一个tid,因为在线程处理函数中首先要分离线程。


连接方式:
在一个终端中打开服务器监听特定端口,在另一个终端或机器上telnet本socket即可连接。

server代码如下:

点击(此处)折叠或打开

  1. #include <unistd.h>
  2. #include <sys/socket.h>
  3. #include <arpa/inet.h>
  4. #include <netinet/in.h>
  5. #include <sys/types.h>
  6. #include <pthread.h>

  7. #include <iostream>
  8. #include <stdlib.h>
  9. #include <strings.h>

  10. using namespace std;

  11. void* worker(void* arg);

  12. int main(int argc, char** argv){
  13.     if(argc != 3){
  14.         cout << "the usage: server ip port." << endl;
  15.         exit(1);
  16.     }

  17.     char* ip = argv[1];
  18.     int port = atoi(argv[2]);

  19.     pthread_t tid;

  20.     int listenfd = socket(AF_INET, SOCK_STREAM, 0);
  21.     if(listenfd == -1){
  22.         cout << "socker() create failed." << endl;
  23.         exit(1);
  24.     }

  25.     struct sockaddr_in server;
  26.     bzero(&server, sizeof(server));
  27.     server.sin_family = AF_INET;
  28.     server.sin_port = htons(port);
  29.     inet_pton(AF_INET, ip, &server.sin_addr);

  30.     if(bind(listenfd, (struct sockaddr*)&server, sizeof(server)) != 0){
  31.     cout << "bind() failed." << endl;
  32.     exit(1);
  33.     }

  34.     if(listen(listenfd, 5) != 0){
  35.         cout << "listen() failed." << endl;
  36.         exit(1);
  37.     }

  38.     while(1){

  39.         struct sockaddr_in client;
  40.         socklen_t client_len = sizeof(client);
  41.     
  42.         int sockfd = accept(listenfd, (struct sockaddr*)&client, &client_len);
  43.         if(sockfd == -1){
  44.             cout << "accept() error." << endl;
  45.             exit(1);
  46.         }
  47.     

  48.         pthread_create(&tid, NULL, worker, (void*)sockfd);
  49.     
  50. //        close(sockfd);
  51.     }
  52.     close(listenfd);

  53.     return 0;
  54. }


  55. void* worker(void* arg){
  56.     pthread_detach(pthread_self());
  57.     char buf[512];
  58.     bzero(&buf, sizeof(buf));
  59.     read((int)arg, &buf, 512);
  60.     write(STDOUT_FILENO, &buf, 512);
  61.     close((int)arg);
  62.     return NULL;
  63. }


阅读(1662) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~