以下是我的套接字客户端程序。我试图从客户端发送一些数据,并尝试在客户端接收它。当我运行程序时,没有编译错误。但我无法在客户端正确接收发送的消息。我想我在做错了
server_reply [len]='\0';
printf("%s\n", server_reply);
我的原始代码如下:(您可以在此链接中找到我的服务器程序Multiple client not getting connected and cannot communicate at the same time)
#include<stdio.h> //printf
#include<string.h> //strlen
#include<sys/socket.h> //socket
#include<arpa/inet.h> //inet_addr
int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server;
char message[1000] , server_reply[2000];
int len;
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while(1)
{
printf("Enter message : ");
scanf("%s" , message);
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
//Receive a reply from the server
if(len = (recv(sock , server_reply , 2000 , 0)) < 0)
{
puts("recv failed");
break;
}
puts("Server reply :");
server_reply [len]='\0';
printf("%s\n", server_reply);
}
close(sock);
return 0;
}
答案 0 :(得分:0)
这条线错了。
if (len = (recv(sock , server_reply , 2000 , 0)) < 0)
{
puts("recv failed");
break;
}
应该是:
if ((len = recv(sock , server_reply , 2000 , 0)) < 0)
{
puts("recv failed");
break;
}