c中的线程服务器

时间:2014-11-30 18:16:27

标签: c multithreading sockets tcp

之前我没有找到我的问题的答案,也不知道是否有我想要做的具体名称,基本上我有一个程序运行模拟,图形界面和后台计算,我想通过命令与tcp基本服务器/客户端控制它,但这意味着我必须在控制功能内部合并服务器功能,所以我在一个线程中使我的服务器,我在主函数中运行的东西,而我在一个线程中调用服务器函数只是为了测试,但我不能向服务器发送任何东西,我的客户端应用程序没有得到响应,服务器没有收到任何东西......代码很乱,因为我正在测试很多其中的东西,而且身份也很混乱......

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>

int test= 0;

void threadServer(){
    int sockfd, newsockfd, portno, clilen;
    char buffer[256];
    struct sockaddr_in serv_addr, cli_addr;
    int  n, c;

    /* First call to socket() function */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
    {
        perror("ERROR opening socket");
        exit(1);
    }
    /* Initialize socket structure */
    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = 5001;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);

    /* Now bind the host address using bind() call.*/
    if (bind(sockfd, (struct sockaddr *) &serv_addr,
                          sizeof(serv_addr)) < 0)
    {
         perror("ERROR on binding");
         exit(1);
    }

    /* Now start listening for the clients, here process will
    * go in sleep mode and will wait for the incoming connection
    */
    listen(sockfd,5);
    clilen = sizeof(cli_addr);
while(c){
    /* Accept actual connection from the client */
    newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, 
                                &clilen);
    if (newsockfd < 0) 
    {
        perror("ERROR on accept");
        exit(1);
    }
    /* If connection is established then start communicating */
    bzero(buffer,256);
    n = read( newsockfd,buffer,255 );
    if (n < 0)
    {
        perror("ERROR reading from socket");
        exit(1);
    }
//if(buffer[0]==t){
//c=0;
//exit(1);
//}else{
//c=1;
//}
    printf("Here is the message: %s\n",buffer);

    /* Write a response to the client */
    n = write(newsockfd,"I got your message",18);
    if (n < 0)
    {
        perror("ERROR writing to socket");
        exit(1);
    }
    test =1;
}
    //return 0; 
}

void main(){

pthread_t threads[1];
   int rc;
   long t;
   char k;
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, threadServer, (void *)t);
      if(rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
     }
    while(1){
    printf("type any key:\n");
    scanf("%c",&k);
    printf("you typed %c\n", k);
    printf("testing server thread : %d\n", test);
    }
   /* Last thing that main() should do */
   pthread_exit(NULL);

}

0 个答案:

没有答案