从Server运行程序并将其连接到同一客户端

时间:2015-02-25 04:52:09

标签: c linux sockets ip port

我正在从客户端向服务器发送hello.c文件。服务器接收它并将其存储为hello123.c。我正在尝试编译此文件并使用system()命令运行它。 在这个hello.c / hello123.c中,我试图连接回同一个客户端。

/* Server Program*/ 
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <signal.h>
#include <ctype.h>          
#include <arpa/inet.h>
#include <netdb.h>

#define PORT 20001 
#define BACKLOG 5
#define LENGTH 512 

int main ()
{
int sockfd; 
int nsockfd; 
int num;
int sin_size; 
struct sockaddr_in addr_local; /* client addr */
struct sockaddr_in addr_remote; /* server addr */
char revbuf[LENGTH];

/* Get the Socket file descriptor */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 )
{
    fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor. (errno = %d)\n", errno);
    exit(1);
}
else 
    printf("[Server] Obtaining socket descriptor successfully.\n");

/* Fill the client socket address struct */
addr_local.sin_family = AF_INET; // Protocol Family
addr_local.sin_port = htons(PORT); // Port number
addr_local.sin_addr.s_addr = INADDR_ANY; // AutoFill local address
bzero(&(addr_local.sin_zero), 8); // Flush the rest of struct

/* Bind a special Port */
if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 )
{
    fprintf(stderr, "ERROR: Failed to bind Port. (errno = %d)\n", errno);
    exit(1);
}
else 
    printf("[Server] Binded tcp port %d in addr 127.0.0.1 sucessfully.\n",PORT);

/* Listen remote connect/calling */
if(listen(sockfd,BACKLOG) == -1)
{
    fprintf(stderr, "ERROR: Failed to listen Port. (errno = %d)\n", errno);
    exit(1);
}
else
    printf ("[Server] Listening the port %d successfully.\n", PORT);

int success = 0;
while(success == 0)
{
    sin_size = sizeof(struct sockaddr_in);

    /* Wait a connection, and obtain a new socket file despriptor for single connection */
    if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, &sin_size)) == -1) 
    {
    fprintf(stderr, "ERROR: Obtaining new Socket Despcritor. (errno = %d)\n", errno);
    exit(1);
    }
    else 
    printf("[Server] Server has got connected from %s.\n", inet_ntoa(addr_remote.sin_addr));


        char buffer[256];
        bzero(buffer,256);
        int n = 0;
        n = read(nsockfd, buffer, 255);
        if (n < 0) error("ERROR reading from socket");
        printf("msg: %s\n",buffer);

    /*Receive File from Client */
    char* fr_name = "hello123.c";
    FILE *fr = fopen(fr_name, "a");
    if(fr == NULL)
    printf("File %s Cannot be opened file on server.\n", fr_name);
    else
    {
    bzero(revbuf, LENGTH); 
    int fr_block_sz = 0;
    while((fr_block_sz = recv(nsockfd, revbuf, LENGTH, 0)) > 0) 
    {
        int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
        if(write_sz < fr_block_sz)
        {
            error("File write failed on server.\n");
        }
        bzero(revbuf, LENGTH);
        if (fr_block_sz == 0 || fr_block_sz != 512) 
        {
            break;
        }
    }
    if(fr_block_sz < 0)
    {
        if (errno == EAGAIN)
        {
            printf("recv() timed out.\n");
        }
        else
        {
            fprintf(stderr, "recv() failed due to errno = %d\n", errno);
            exit(1);
        }
    }
    printf("Ok received from client!\n");
    fclose(fr); 

    }
    system("gcc hello123.c -o hello123.out");
    system("./hello123.out");


}

}

以下是客户端计划。

 /* Client Program */   
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <signal.h>
#include <ctype.h>          
#include <arpa/inet.h>
#include <netdb.h>

#define PORT1 20001
#define PORT2 20002
#define LENGTH 512 

int main(int argc, char *argv[]){
int sockfd; 
int nsockfd;
char revbuf[LENGTH]; 
struct sockaddr_in remote_addr;
struct sockaddr_in server;
struct sockaddr_in dest;
int status,socket_fd, client_fd,num;
socklen_t size;

char buffer[1024];
char *buff, ch;

/* Get the Socket file descriptor */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
    fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor! (errno = %d)\n",errno);
    exit(1);
}

/* Fill the socket address struct */
remote_addr.sin_family = AF_INET; 
remote_addr.sin_port = htons(PORT1); 
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr); 
bzero(&(remote_addr.sin_zero), 8);

/* Try to connect the remote */
if (connect(sockfd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1)
{
    fprintf(stderr, "ERROR: Failed to connect to the host! (errno = %d)\n",errno);
    exit(1);
}
else 
    printf("[Client] Connected to server at port %d...ok!\n", PORT1);

/* Send File to Server */
//if(!fork())
//{
    char* fs_name = "hello.c";
    char sdbuf[LENGTH]; 

       // char buffer[256];
        int n;
        fgets(buffer,255,stdin);
       // bzero(buffer,256);
        n = write(sockfd,buffer, strlen(buffer));
        if(n<0) printf("Error: sending filename");

    printf("[Client] Sending %s to the Server... ", fs_name);
    FILE *fs = fopen(fs_name, "r");
    if(fs == NULL)
    {
    printf("ERROR: File %s not found.\n", fs_name);
    exit(1);
    }

    bzero(sdbuf, LENGTH); 
    int fs_block_sz;
    while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
    {
    if(send(sockfd, sdbuf, fs_block_sz, 0) < 0)
    {
        fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", fs_name, errno);
        break;
    }
    bzero(sdbuf, LENGTH);
    }
    printf("Ok File %s from Client was Sent!\n", fs_name);
//}

//while(1) {
remote_addr.sin_family = AF_INET; 
remote_addr.sin_port = htons(PORT2); 
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr); 
bzero(&(remote_addr.sin_zero), 8);

size = sizeof(struct sockaddr_in);

if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) 
{
    perror("accept");
    exit(1);
}
printf("Server got connection from client %s\n", inet_ntoa(dest.sin_addr));

while(1) {

    if ((num = recv(client_fd, buffer, 1024,0))== -1) {
            perror("recv");
            exit(1);
    }
    else if (num == 0) {
            printf("Connection closed\n");
            //So I can now wait for another client
            break;
    }
    buffer[num] = '\0';
    printf("Server:Msg Received %s\n", buffer);


}//End of Inner While...
//Close Connection Socket
close(client_fd);

close (sockfd);
printf("[Client] Connection lost.\n");
return (0);


}

以下是Hello.c

/* Hello.c */   
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 20002
#define MAXSIZE 1024
#define SA struct sockaddr
int main(int argc, char *argv[])
{   
    int sockfd,connfd;
    struct sockaddr_in server_info;
    struct hostent *he;
    int socket_fd,client_fd,num;
    char buffer[1024];
    char i;

    char buff[1024];
    struct sockaddr_in servaddr,cli;
    sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd==-1)
        {
        printf("Hello:socket creation failed...\n");
        exit(0);
        }
    else
        printf("Hello:Socket successfully created..\n");
    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family=AF_INET;
    servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
    servaddr.sin_port=htons(PORT);
    if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))!=0)
        {
        printf("Hello:connection with the server failed...\n");
        exit(0);
        }
    else
        printf("Hello:connected to the server..\n");




    printf("\n Hello:Choose between 1 and 2\n");


    printf("Hello:Enter Data for Server:\n");
    fgets(buffer,MAXSIZE,stdin);
     if ((send(socket_fd,buffer, strlen(buffer),0))== -1) {
            fprintf(stderr, "Hello:Failure Sending Message\n");
            close(socket_fd);
            exit(1);
    }

    else {
            printf("Hello:Client:Message being sent: %c\n",i);



    close(socket_fd);


}
}

运行程序时,文件传输成功。但是Hello.c没有连接到客户端。 这是我的输出

服务器端:

$ ./server24.out
[Server] Obtaining socket descriptor successfully.
[Server] Binded tcp port 20001 in addr 127.0.0.1 sucessfully.
[Server] Listening the port 20001 successfully.
[Server] Server has got connected from 127.0.0.1.
msg: 

Ok received from client!
Hello:Socket successfully created..
Hello:connection with the server failed...

客户端:

$ ./client24.out
[Client] Connected to server at port 20001...ok!

[Client] Sending hello.c to the Server. Ok File hello.c from Client was Sent
accept: Socket operation on non-socket

我猜这是一些地址问题。但我无法弄明白。 请帮忙。

提前致谢。

1 个答案:

答案 0 :(得分:1)

因此,您的客户端程序开始充当server,但您尚未创建必要的socket来接受其中的连接。来自socket_fd

socket()未被初始化使用

需要在客户

中的//while(1) {之后添加更新
//while(1) {
/* Get the Socket file descriptor */
if ((socket_fd= socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
    fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor! (errno = %d)\n",errno);
    exit(1);
}

/* Fill the socket address struct */
remote_addr.sin_family = AF_INET; 
remote_addr.sin_port = htons(PORT2); 
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr); 
bzero(&(remote_addr.sin_zero), 8);

if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) 
{
    perror("accept");
    exit(1);
}