我是 C 套接字编程的新手,我想构建一个服务器/客户端应用程序,其中客户端从文本文件(46mb)读取部分数据并将其发送到服务器,我希望服务器打印接收到的部分文件到控制台。
我做错了吗?服务器此时将空行打印到控制台。我不知道为什么:/
这是客户端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(char *msg) {
perror(msg);
exit(1);
}
int main( int argc , char *argv[] ) {
int sockfd , port_no , n;
struct sockaddr_in server_addr;
struct hostent *server;
char buffer[256];
FILE *fp;
if(argc < 3) {
fprintf(stderr , "usage %s hostname port" , argv[0] );
exit(0);
}
port_no = atoi( argv[2] );
sockfd = socket( AF_INET , SOCK_STREAM , 0);
if( sockfd < 0 )
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if( server == NULL ) {
fprintf(stderr , "ERROR, no such host.");
exit(0);
}
bzero( (char *) &server_addr , sizeof(server_addr) );
server_addr.sin_family = AF_INET;
bcopy( (char *)server -> h_addr , (char *) &server_addr.sin_addr.s_addr , server -> h_length );
server_addr.sin_port = htons(port_no);
if( connect( sockfd , (char *) &server_addr , sizeof(server_addr)) < 0 ) {
error("ERROR , connecting");
}
bzero(buffer , 256);
if( (fp = fopen("text.txt" , 'r')) != NULL ) {
while(1) {
if( (fgets(buffer , 255 , fp)) != NULL ) {
n = write( sockfd , buffer , strlen(buffer) );
if( n < 0 ) {
error("ERROR writing to socket");
}
}
}
fclose(fp);
}
}
这是服务器:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(char *msg) {
perror(msg);
exit(1);
}
int main(int argc , char *argv[]) {
int sockfd , newsockfd , port_no , cli_length , n;
char buffer[256];
struct sockaddr_in server_addr , client_addr;
if(argc < 2) {
fprintf(stderr , "ERROR , no port provided!");
exit(1);
}
sockfd = socket(AF_INET , SOCK_STREAM , 0);
if( sockfd < 0 )
error("ERROR opening socket.");
bzero( (char *) &server_addr , sizeof(server_addr) );
port_no = atoi(argv[1]);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons( port_no );
server_addr.sin_addr.s_addr = INADDR_ANY;
if( bind( sockfd , (struct sockaddr *) &server_addr , sizeof(server_addr)) < 0 ) {
error("ERROR on binding.");
}
listen(sockfd , 5);
cli_length = sizeof(&client_addr);
newsockfd = accept( sockfd , (struct sockaddr *) &client_addr , &cli_length );
if (newsockfd < 0 )
error("ERROR on accept.");
bzero(buffer , 256);
while(1) {
n = read(newsockfd , buffer , 255);
if( n < 0 ) {
error("ERROR reading from socket");
}
printf(" %s " , buffer);
}
}