我正在尝试编写一个简单的客户端 - 服务器单向聊天(仅用于学习目的),但我一开始就陷入困境。这些是服务器和客户端的代码
服务器:
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <netinet/in.h>
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include <stdio.h> /* for perror() */
#include <stdlib.h> /* for exit() */
#include <string.h>
#define MYPORT 3490
int main(int argc, char *argv){
struct sockaddr_in my_addr;
struct sockaddr_in cli_addr;
int sockfd;
int newsockfd;
socklen_t clilen;
int n;
char client_message[2000];
//socket declaration
sockfd = socket(AF_INET, SOCK_STREAM, 0);
//filling struct
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(MYPORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
memset(& (my_addr.sin_zero), '0', 8);
//binding socket to address and port
if(bind(sockfd, (struct sockaddr *)& my_addr, sizeof(my_addr))<0)
printf("Bind error");
//listening on the socket
listen(sockfd, 5);
printf("Waiting for connection...\n");
clilen = sizeof(cli_addr);
//accepting connection
if (newsockfd = accept(sockfd, (struct sockaddr *)& cli_addr, &clilen) <0){
printf("Unable to connect\n");
}
else
{
printf("Connected with %s\n", inet_ntoa(cli_addr.sin_addr));
}
while( (n = recv(newsockfd , client_message , 2000 , 0)) > 0 )
{
printf(client_message);
}
if(n == 0)
{
printf("Client disconnected");
}
else if(n == -1)
{
printf("recv failed");
}
}
客户端:
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <netinet/in.h>
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include <string>
int main(int argc, char * argv[]){
int n;
int client;
int dest_port = 3490;
char buffer[1000];
struct sockaddr_in server_addr;
client = socket(AF_INET, SOCK_STREAM, 0);
printf("Socket created\n");
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(dest_port);
server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
memset(&(server_addr.sin_zero),'0',8);
if(connect(client, (struct sockaddr*)&server_addr, sizeof(server_addr))<0)
printf("Connection error");
printf("Connected with server\n");
while(1)
{
printf("Enter message : ");
scanf("%s" , buffer);
//Send some data
if( send(client , buffer , strlen(buffer) , 0) < 0)
{
printf("Send failed");
return 1;
}
}
}
服务器输出如下:
Waiting for connection...
Connected with 127.0.0.1
recv failed
输出客户端时
Socket created
Connected with server
Enter message :
我花了几个小时阅读教程,手册页和其他内容,我真的无法解决这个问题。问题似乎并不那么复杂,所以我更加不安。 此外,当尝试从服务器发送并在客户端接收时,我已经发送&#34;发送失败&#34;在服务器端。
编辑: 在使用perror并找出&socket;非套接字&#34;套接字操作后#34;意思是我发现问题是
if (newsockfd = accept(sockfd, (struct sockaddr *)& cli_addr, &clilen) <0)
第一次合作&#34;接受......&#34;用&#34; 0&#34;然后将比较结果分配给newsockfd
。