socket编程中的线程问题

时间:2015-09-24 15:43:36

标签: linux multithreading sockets pthreads

我有以下代码..

server.c

       #ifndef __TCP_H__
       #     define __TCP_H__

       typedef struct {

            int recipientId;    // this is the reciever ID
            char data[1024];           // this is the main data part

           }Packet;


       #endif /* __TCP_H__ */

tcp.h 看起来像

 #include <stdio.h>
 #include "./../linux.h"
 #include "./tcp.h"
 #include <pthread.h>

 void print(void);
 void scan(void);
 int sock_fd;
 int main(int argc, char** argv) {
 if (argc != 3){
     printf("\nUsage: ./client port_number server_ip\n");
     return 1;
  }
 static struct sockaddr_in sock;
 int len;
 pthread_t thread1, thread2;
 sock_fd = socket(PF_INET, SOCK_STREAM, 0);
 if (sock_fd == -1){
   perror("socket");
   exit(1);
 }
 sock.sin_family = PF_INET;
 sock.sin_port = htons(atoi(argv[1]));
 sock.sin_addr.s_addr  = inet_addr(argv[2]);
 len = sizeof(sock);
 if ( connect(sock_fd, (struct sockaddr *)&sock , len) == -1 ){
   perror("connect");
   exit(1);
 }

 pthread_create(&thread1, NULL, (void*)&print, NULL);
 pthread_create(&thread2, NULL, (void*)&scan, NULL);

 pthread_join(thread1, NULL);
 pthread_join(thread2, NULL);


 return 0;
}

 void print(){
   char messege[1024];
   while(1){
   if (read(sock_fd, messege, 1024) == -1){
     perror("read");
     return;
   }
   printf("messege = %s\n", messege);
  }
 pthread_exit(0);
 }

  void scan(void){
    Packet packet;
    while(1){
      printf("Enter the reciver ID: ");
      scanf("%d", &packet.recipientId);
      printf("Enter the data: ");
      scanf("%s", packet.data);
      if ( write(sock_fd, &packet, sizeof(packet)) == -1) {
        perror("read");
        return;
      }
   }
   pthread_exit(0);
  }

每个 client.h 都是这样的

threadCount

现在问题是

  1. 当我运行服务器&amp;在2个终端中,每个客户端被接受后的2个客户端pthread_join应该在服务器端打印但不打印。这意味着执行在第一个class EventPage(Page)之后停止/跳过但为什么 ??

  2. 连接两个线程后,当我将数据从第一个客户端发送到第一个客户端本身时,它工作但不是从第一个客户端到第二个客户端..它正在发送到服务器终端窗口。 为什么?

  3. 从第二个客户端发送时无效(发送自身或客户端1).. 为什么?

  4. 请帮忙..感谢您耐心阅读上述所有代码。

1 个答案:

答案 0 :(得分:0)

TCP是字节流协议,而不是消息协议。您正在调用TCP函数并期望它们发送或接收消息。他们没有。如果要发送或接收消息,则必须实现消息协议,编写发送和接收消息的函数,然后调用这些函数。

if (read(sock_fd, messege, 1024) == -1){
  perror("read");
  return;
}
printf("messege = %s\n", messege);

printf的来电是一场灾难。 %s格式说明符用于C样式字符串,而不是从字节流接收的任意字节块。最明显的方法是看看它有多糟糕,请考虑一下--- printf应该如何决定打印多少字节?在将它与-1进行比较后,您丢弃了返回的值read,因此您不知道收到了多少字节。

我确定您的代码存在其他问题,但基本设计被破坏的事实使得修复这些问题变得不值得。相反,设计一个消息协议并实现它。