简体   繁体   English

套接字中的数据发送错误

[英]Data sending error in socket

I have made simple server and client in c.Client waits for server until server is started.When i start the server data transmission between server and client is happening as per my expectation.When i close the server(not client) and again restarts the server,the first string from client to server is not transmitting.and then afterwards the client can send strings to server.So after restarting server client can't transmit first string to server. 我在c中创建了简单的服务器和客户端。客户端等待服务器直到服务器启动。当我启动服务器时,服务器和客户端之间的数据传输符合我的期望。当我关闭服务器(不是客户端)并再次重新启动时服务器,从客户端到服务器的第一个字符串不传输。然后,客户端可以将字符串发送到服务器。因此,重新启动服务器后,客户端无法将第一个字符串传输到服务器。 Here is my client code(client.c), 这是我的客户代码(client.c),

 /*header*/
#include<signal.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
/*macros*/
/*size of the buffer*/
#define DATA_SIZE 200
/*function for thread*/
void *recieve_handler(void *);
/*stores the id of main thread*/
pthread_t main_id;
/*socket variable*/
int sockfd=0;
/*specifies the port number*/
#define PORT 5000
/*lenth of ip*/
#define LENGTH_OF_IP 100
int quit = 1;
void signal_handler(int n)
{
    /*write null to server*/
    write(sockfd,"",2);
    /*close socket*/
    close(sockfd);
    printf("Exiting from applicationn");
    exit(0);
}
int main(int argc, char *argv[])
{
    /*buffer to send and receive*/
    char received_data[DATA_SIZE],send_data[DATA_SIZE],server_ip[LENGTH_OF_IP],buf[DATA_SIZE]
    ,user_name[DATA_SIZE];
    /*declare pointer for client config file*/
    FILE* config_file;
    /*flags*/
    int clear = 1,server_port,usb_trap_on,n;
    /*declaring socket object*/
    struct sockaddr_in serv_addr;
    /*thread declaration*/
    pthread_t thread_id;
    /*welcome messsage*/
    printf("This is clientn");
    printf("Enter somethingn");
    printf("Server echos back the datan");
    /*open client configuration file*/
    if ((config_file = fopen("client.config","rw+")) == NULL)
    {
        printf("Could not open client config filen");
        return 1;
    }
    /*parsing the file*/
    while (fgets(buf, sizeof buf, config_file) != NULL) {
        if (sscanf(buf,"IP=%s PORT=%d",server_ip,&server_port) == 2)
        printf("%s %dn",server_ip,server_port);
        if (fscanf(config_file,"usb_trap=%d",&usb_trap_on) == 1)
        printf("usb flag is %dn",usb_trap_on);
    }
    /*create the socket*/
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        printf("n Error : Could not create socket n");
        return 1;
    }
    /*By setsockopt kernal will release the socket
    *if it is in use*/
    if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&clear,sizeof(int)) == -1) {
        perror("setsockopt");
        exit(1);
    }
    /*inialize all the variable of object serv_addr with 0*/
    memset(&serv_addr, '0', sizeof(serv_addr));
    /*AF_INET refers to addresses from the internet*/
    serv_addr.sin_family = AF_INET;
    /*specifies port address
    *and The htons() function makes sure that numbers are stored
    *in memory in network byte order, which is with the most
    *significant byte first*/
    serv_addr.sin_port = htons(server_port);
    /* inet_pton - convert IPv4 and IPv6 addresses from text to binary form
    * it returns 0 when coversion is unsucessful*/
    if(inet_pton(AF_INET, server_ip, &serv_addr.sin_addr)<=0){
        printf("n inet_pton error occuredn");
        return 1;
    }
    /*connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))
    *if connection is established then the memory for server will be
    *allocated in client's memory
    *and strting address of that memory is stored in scokfd
    *i will return negative value if operation fails. */
    while(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
        printf("Wating for server to connectn");
        sleep(1);
    }
    printf("Connection is donen");
    printf("enter somethingn");
    /*signal handling*/
    signal(SIGTSTP,signal_handler);
    /*create the thread to receive data*/
    if( pthread_create( &thread_id , NULL , recieve_handler , (void*)&sockfd) < 0) {
        perror("could not create thread");
        return 1;
    }
    while(1) {
        /*clear the buffer*/
        memset(received_data,0,DATA_SIZE);
        /*read from server*/
        n = read(sockfd,received_data,sizeof(received_data));
        /*if read error is occurred*/
        if (n < 0) {
            printf("Can't read received_datan");
            break;
            pthread_exit(&n);
        }
        if(n == 0) {
            printf("Can't read received_datan");
            break;
        }
        puts(received_data);
    }
    pthread_cancel(&thread_id);
    /*close socket*/
    if(!close(sockfd))
    printf("Socket is closedn");
    printf("Server is sutdown!!!!!!!!!!!!!n");
    system("./client");
    return 0;
}
void *recieve_handler(void *socket_desc)
{
    /*received data buffer*/
    char send_data[DATA_SIZE];
    /*status flag*/
    int n;
    /*if pointer is empty*/
    if(socket_desc == NULL) {
        printf("socket_desc is NULLn");
        n = 0;
        pthread_exit(&n);
    }
    /*socket number*/
    int sock = *(int*)socket_desc;
    /*infinite loop*/
    while (1){
        /*clear buffer*/
        memset(send_data, '0', sizeof(send_data));
        /*get data from user*/
        gets(send_data);
        if((write(sock, send_data, strlen(send_data)+1)) == -1)
        {
            /*write data to server*/
            printf("could not writen");
            break;
        }
    }
}

here is my server code(server.c), 这是我的服务器代码(server.c),

/*header*/
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h> 
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h> 

/*macros*/

/*maximum client that can be connected to server*/
#define MAX_CLIENT 10

/*size of the buffer*/
#define DATA_SIZE 200

/*specifies the port number*/
#define PORT 7000

int listenfd;

void signal_handler(int n)

{


printf("In handler\n");
char recived_data[DATA_SIZE];
 write(listenfd,"\0",2);

read(listenfd, recived_data, sizeof(recived_data));/*write null to server*/

    write(listenfd,"\0",2);


    /*close socket*/

    close(listenfd);



    printf("Exiting from application\n");



    exit(0);

}

int main(int argc, char *argv[])
{


    /*signal handling*/
    signal(SIGTSTP,signal_handler);

    /*to store the recived data*/
    char recived_data[DATA_SIZE];   

    /*sockaddr_in is a structure defined in netinet/in.h file.we are creating object of that
     *strucure. */
    struct sockaddr_in serv_addr;

    /*flags*/
    int  connfd = 0 , clear = 1 ;

    /*welcome message*/
    printf("This simple server\n");
    printf("It will echo data to client\n");
    printf("If quit is recived from client then server will be existed\n");

    /*Created socket*/
    if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        printf("Can't create socket\n");
    }

    /*By setsockopt kernal will release the socket
     *if it is in use*/
    if (setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&clear,sizeof(int)) == -1) {
        perror("setsockopt");
        exit(1);
    }

    /*AF_INET refers to addresses from the internet*/
    serv_addr.sin_family = AF_INET;

    /*tells that any client can connect*/
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    /*specifies port address 
     *and The htons() function makes sure that numbers are stored 
     *in memory in network byte order, which is with the most 
     *significant byte first*/
    serv_addr.sin_port = htons(PORT);

    /*specifies  port and adress of the socket*/ 
    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    /*it will listen for connection
     *MAX_CLIENT specifies the maximum client server can handle*/
    listen(listenfd, MAX_CLIENT); 

    /*accept will assign the memory to client in server's memory area.here 
     *connfd has starting adress of  assigned memory to client in server 
     *memory.*/
    connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);


    /*inet_ntoa(serv_addr.sin_addr) will return the adress of client*/
    printf("[Server] Server has got connected from %s.\n", inet_ntoa(serv_addr.sin_addr));


        printf("server waiting\n");

    while(1){

        /*read the data from memory and put in buffer*/
        if(read(connfd, recived_data, sizeof(recived_data))){

            /*if quit is recived then break the loop*/
            if(!strcmp(recived_data,"quit"))
                break; 

            /*put data on screen*/
            puts(recived_data);

            /*echo the data back to client*/
            if(write(connfd,recived_data,strlen(recived_data)+1) == -1)
                break;  

        }

        else
        {
            printf("Could not read\n");
        }
    }

    read(connfd, recived_data, sizeof(recived_data));    
    printf("server exiting\n");

    /*close socket*/
    close(connfd);

    return(0);

}

here is client.config file(which is used be client to get ip,port of server) 这是client.config文件(用于客户端获取ip,服务器端口)

IP=192.168.3.17 PORT=7000

usb_trap=0

This is my output of client when server is first time connected, 这是我第一次连接服务器时客户端的输出,

This is client
Enter something
Server echos back the data
192.168.3.17 7000
usb flag is 0
Wating for server to connect
Wating for server to connect
Connection is done
enter something
hello
hello
i am jay
i am jay

Above output is as per my expectation. 上面的输出符合我的期望。

Now below is my output of client when server is reconnected(server is disconnected ,and then started again) 现在下面是重新连接服务器时客户端的输出(服务器断开连接,然后再次启动)

Socket is closed
Server is sutdown!!!!!!!!!!!!!
This is client
Enter something
Server echos back the data
192.168.3.17 7000
usb flag is 0
Wating for server to connect
Wating for server to connect
Wating for server to connect
Wating for server to connect
Connection is done
enter something
hello
could not write
jay
jay

So in above output client can't write first string to server. 因此,在上面的输出中,客户端无法将第一个字符串写入服务器。

Client signal handler: 客户端信号处理程序:

void signal_handler(int n)
{
    /*write null to server*/
    write(sockfd,"",2);
    /*close socket*/
    close(sockfd);
    printf("Exiting from applicationn");
    exit(0);
}

Everything wrong here that could be wrong. 这里所有可能是错误的错误。 No error checking. 没有错误检查。 You can't do I/O in signal handlers. 您不能在信号处理程序中执行I / O。 You can't block in signal handlers. 您不能阻止信号处理程序。 You don't need to 'write null to server'. 您不需要“将null写入服务器”。 Exiting the application will close the socket, or reset it. 退出应用程序将关闭套接字,或将其重置。

Client: 客户:

while(1) {
    /*clear the buffer*/
    memset(received_data,0,DATA_SIZE);

Unnecessary. 不必要。 Remove. 去掉。

    if (n < 0) {
        printf("Can't read received_datan");

A pointless message. 无意义的消息。 You got an error. 您遇到了错误。 Print the error, with perror() , or by incorporating strerror() into the message. 使用perror()或通过将strerror()合并到消息中来打印错误

    if(n == 0) {
        printf("Can't read received_datan");

An incorrect message. 错误的消息。 This situation is not the same as the previous one. 这种情况与前一种情况不同。 You got end of stream. 您已结束流。 The peer has disconnected. 对等体已断开连接。 Say so. 这样说的。

    puts(received_data);

Wrong. 错误。 The data received is only valid up to n bytes. 接收到的数据仅有效至n个字节。 The correct way to print it is via printf("%.*s", n, received_data); 正确的打印方法是通过printf("%.*s", n, received_data);

Client 'receive handler': 客户端“接收处理程序”:

void *recieve_handler(void *socket_desc)

Apart from the mis-spelling, why is this called a receive handler when it doesn't receive? 除了拼写错误外,为什么它在不接收时被称为接收处理程序? and does send? 并发送?

 memset(send_data, '0', sizeof(send_data));
 /*get data from user*/
 gets(send_data);

You probably meant '\\0' here, as there are numerous other backslashes missing from your code, but the memset() is completely unnecessary. 您可能在这里的意思是'\\0' ,因为代码中还有许多其他反斜杠,但是memset()完全没有必要。 Remove. 去掉。

Server signal handler: 服务器信号处理程序:

void signal_handler(int n)
{
    printf("In handler\n");
    char recived_data[DATA_SIZE];
    write(listenfd,"\0",2);
    read(listenfd, recived_data, sizeof(recived_data));/*write null to server*/
    write(listenfd,"\0",2);
    /*close socket*/
    close(listenfd);
    printf("Exiting from application\n");
    exit(0);
}

This is all nonsense from start to finish. 从头到尾都是废话。 You can't do I/O in a signal handler; 您不能在信号处理程序中执行I / O; you can't do I/O with a listening socket; 您不能使用监听套接字进行I / O; you can't block in a signal handler; 您不能阻止信号处理程序; and you don't need to do any of it. 而且您无需执行任何操作。 The operating system will either close or reset the socket. 操作系统将关闭或重置套接字。 Either way the peer will find out via the return value of read() or recv() . 无论哪种方式,对等方都可以通过read()recv()的返回值来查找。

Server loop: 服务器循环:

    if(read(connfd, recived_data, sizeof(recived_data))){

Incorrect. 不正确。 It is never correct to call read() or recv() without storing the return value into a variable. 如果未将返回值存储到变量中,则调用read()recv()永远是不正确的。 You have to test it for -1, test it for zero, and otherwise use it as the length of data received. 您必须将其测试为-1,将其测试为零,否则将其用作接收的数据长度。 You can't accomplish that without a variable. 没有变量,您将无法完成。 See your own client code for an example, after my corrections. 经过更正后,请参见您自己的客户端代码作为示例。

        if(!strcmp(recived_data,"quit"))

Invalid. 无效。 There is no guarantee that you will receive a null-terminated string. 不能保证您会收到一个以空值结尾的字符串。 And you haven't checked for EOS or an error first. 而且您还没有先检查EOS或错误。

        puts(recived_data);

Invalid for the same reason as the puts() in the client as discussed above. 无效的原因与上述客户端中的puts()相同。

        if(write(connfd,recived_data,strlen(recived_data)+1) == -1)

Invalid. 无效。 The length of the data received is given by the return value of read() if positive, not by strlen(). 接收到的数据的长度由read()的返回值read()如果为正)而不是strlen(). See discussion above. 参见上面的讨论。

    else
    {
        printf("Could not read\n");
    }

See discussion above about indiscriminate error messages like this. 请参阅上面有关此类随意错误消息的讨论。 No use at all. 完全没有用。

read(connfd, recived_data, sizeof(recived_data));    

What is this? 这是什么? Remove. 去掉。

Problem is that you are not canceling the thread properly. 问题是您没有正确取消线程。

Use 采用

pthread_cancel(thread_id);

instead of 代替

pthread_cancel(&thread_id);

So now thread will be canceled.and that thread will not be lived. 所以现在线程将被取消。该线程将不被使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM