【问题标题】:Multithreaded chat in windows C++Windows C++ 中的多线程聊天
【发布时间】:2016-06-06 23:13:03
【问题描述】:

我正在尝试进行简单的多线程客户端/服务器聊天,但我遇到了一个问题,程序进入循环而没有显示任何消息,我所拥有的只是消息“已接收:”,仅此而已。 这里的代码 服务器代码:

#pragma comment(lib, "WS2_32.lib") // link with Ws2_32.lib
#include <Winsock2.h>
#include <Windows.h>
#include <iostream>
#include <cstdio>
#include <pthread.h>

#define DEFAULT_PORT 54345

using namespace std;

void *receive(void *)
{
    SOCKET client;
    long app;
    char buff[256];
    memset(&buff,0,sizeof(buff));
    while(1)
   {
        memset(&buff,0,sizeof(buff));
        app=recv(client,buff,sizeof(buff), 0);
        if(app<0) cout<<" Can't get message"<<endl;
        else cout<<"Client: "<<buff<<endl;  
    }
}

int main() 
{
    pthread_t threadA[5];
    cout<<"Server TCP/IP"<<endl; 
    char recvbuf[256]; //buff ti get message
    char serverAddrStr[256]={'\0'}; //Contain the IP address
   #ifdef WIN32       
   WSADATA wsaData;
   WSAStartup (0x0101,&wsaData);
   #endif
   long res; 
   WSADATA wsadata; 
   res = WSAStartup(MAKEWORD(2, 1), &wsadata); //Initialize winsock
   if(res==0) cout<<"Winsocket initialized!"<<endl;   
   else cout<<"Error initializing winsocket"<<endl;
   SOCKET slisten,client; //Socket Descriptor
   cout<<"IP address to connect: ";
   cin.getline(serverAddrStr,256);
   slisten=socket(AF_INET,SOCK_STREAM,0); 
   if(slisten!=INVALID_SOCKET) cout<<"Socket created!"<<endl;
   else cout<<"Error creating socket"<<endl;
   //info of the socket
   sockaddr_in info; //sockaddr
   info.sin_addr.s_addr=INADDR_ANY; //accept anyone
   info.sin_family=AF_INET; 
   info.sin_port=htons(54345); //Convert the porta in the order (big-endian) of TCP/IP 
   int infolen=sizeof(info); //Contain dimension ofsockaddr
   res=bind(slisten,(struct sockaddr*)&info, infolen); 
   if(res!=SOCKET_ERROR) cout<<"Connessione estabilished!"<<endl; 
   else cout<<"Connection error..."<<endl;
   res=listen(slisten,SOMAXCONN); 
   if(res!=SOCKET_ERROR) cout<<"I'm on the port 54345"<<endl; 
   else cout<<"Can't listen on port 54345"<<endl;
   sockaddr_in clientinfo; //Info of the client
   int clientinfolen=sizeof(clientinfo); 
int nthread=0;
   while(nthread<5) 
   {
       clientinfolen= sizeof(clientinfo);
       cout<<"I'm waiting a client"<<endl;
       client=accept(slisten,(struct sockaddr*)&clientinfo,&clientinfolen); 
       if(client<0) 
       {
           cout<<"Can't accept connection"<<endl;
           return 0;
       }
       cout<<"Connection estabilished"<<endl;
       res=pthread_create(&threadA[nthread],NULL,receive,NULL);
       if(res!=0) cout<<"Error creating thread"<<endl;
       nthread++;
   }
   for(int i=0;i<5;i++) pthread_join(threadA[i],NULL);
   closesocket(client); 
   closesocket(slisten); 
   WSACleanup(); 

   system("PAUSE");
   return 0;
}

这里是客户端代码:

#pragma comment(lib,"ws2_32.lib")
#include <cstdio>
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>

using namespace std;

int main() 
{
     cout<<"Client TCP/IP"<<endl;
     char sendbuf[256]; //Buffer to send
     long res; 
     WSADATA wsadata; 
     SOCKET sConnect; 
     sockaddr_in conpar;
     res=WSAStartup(MAKEWORD(2,0),&wsadata); 
     if(res==0) cout<<"Winsock initialized!"<<endl; 
     else cout<<"Winsock initializing failed"<<endl;
     sConnect=socket(AF_INET,SOCK_STREAM,0); //Create the socket
     if(sConnect!=INVALID_SOCKET) cout<<"Socket created!"<<endl; 
     else cout<<"Errore creating socket, error: "<<WSAGetLastError()<<endl;
     hostent *serverInfo; //Info of the host
     char serverAddrStr[256]; //IP address
     cout<<"IP address: ";
     cin.getline(serverAddrStr,256); 

     conpar.sin_addr.S_un.S_addr=inet_addr(serverAddrStr); //IP address to connect
     conpar.sin_family=AF_INET; 
     conpar.sin_port=htons(54345); //Port to connect in big endian format
     int conparlen=sizeof(conpar); 
     res=connect(sConnect,(struct sockaddr*)&conpar,conparlen); //Connection
     if(res!=SOCKET_ERROR) cout<<"Connessione estabilished!"<<endl; 
     else cout<<"Connection failed, error: "<<WSAGetLastError()<<endl;
     while(1) 
     {
         memset(&sendbuf,0,sizeof(sendbuf)); 
         cout<<"Send: ";
         cin.getline(sendbuf,256);; //Get message
         res=send(sConnect,sendbuf,strlen(sendbuf),0); 
     }
     closesocket(sConnect); 
     WSACleanup(); 

     system("PAUSE");
     return 0;
 }

我在安装包的windows系统中使用posix线程。

【问题讨论】:

  • 哦,天哪...该代码无法读取,它只是一堵无法辨认的噪音墙!请在其中添加一些间距和换行符。意大利语(?)中的 cmets 也没有多大帮助,至少对我们不懂意大利语的人(这是这里的大多数人)没有多大帮助。
  • 对不起,我翻译了代码:)

标签: c++ multithreading server client chat


【解决方案1】:

您的 receive 函数永远不会将 client 设置为合理的值。您还有很多其他问题,但这是最明显的。

void *receive(void *)
{
    SOCKET client; // ** Create variable
    long app;
    char buff[256];
    memset(&buff,0,sizeof(buff));
    while(1)
    {
        memset(&buff,0,sizeof(buff));
        app=recv(client,buff,sizeof(buff), 0); // ** Use variable
        if(app<0) cout<<" Can't get message"<<endl;
        else cout<<"Client: "<<buff<<endl;  
    }
}

它在哪里设置为合理的值?

您似乎也错误地理解为在 TCP 连接上调用 recv 会收到一条消息。这不是真的。如果你想要一个接收消息的函数,你必须写一个。

【讨论】:

  • 我不明白,什么意思?
  • 你不明白什么?
  • 我没明白你的敏感值是什么意思
  • 我的意思是一个对应于实际连接的值。你根本没有设置它。查看我的更新。
  • 我必须使用哪种类型的变量?我应该如何使用它?
猜你喜欢
  • 2014-07-27
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
相关资源
最近更新 更多