我有一个客户端(c++)/服务器(c)程序,目前我很难在它们之间进行通信(我看不到客户端在服务器上说什么,反之亦然)。我也在尝试让这个项目多线程,或者至少接受来自客户端的多个连接。非常感谢所有帮助是与聊天有关的代码,您可以在此处完整查看
客户:
recv(sockfd , server_reply , 2000 , 0);
puts("Enter message :"); // asking for password
scanf("%s" , message);
send(sockfd , message , strlen(message) , 0);
recv(sockfd, server_reply, 2000, 0);
//Receive a reply from the server
if( recv(sockfd , server_reply , 2000 , 0) < 0)
{
puts("recv failed");
}
while( (read_size = recv(nsockfd , server_reply , 4000 , 0)) != 0)
{
puts("Enter message :"); // asking for password
scanf("%s" , message);
send(sockfd , message , strlen(message) , 0);
recv(sockfd, server_reply, 2000, 0);
}
服务器
char client_address[90];
sprintf(client_address, "Welcome %s", inet_ntoa(addr_remote.sin_addr));
char welc_msg[90] = "Welcome %s";
char friend_msg[50] = "Hello little friend \n";
char username[30] = "Enter user:";
char pass[30] = "Enter pass: ";
write(nsockfd , client_address , strlen(client_address)); // attempting to send client "Hello, (their ip address)"
read_size = recv(nsockfd , client_message , 4000 , 0);
read_size = recv(nsockfd , client_message , 4000 , 0);
printf( "%s", client_message);
printf( "\n");
//Receive a message from client
while( 1 ) // while( (read_size = recv(nsockfd , client_message , 4000 , 0)) != 0)
{
//clearing buffer
memset(client_message, 0, sizeof(client_message));
//taking received message and printing it
read_size = recv(nsockfd , client_message , 4000 , 0);
printf( "%s", client_message);
printf( "\n");
//Send the message back to client
// write(nsockfd , server_message , strlen(server_message));
if (strcmp(client_message , "Hello")) // condition for project
{
write(nsockfd, friend_msg, strlen(friend_msg));
}
}