阅读背景:

从客户端向服务器发送字符串

来源:互联网 

I wrote this:

我写了这个:

Client:

printf("\nType a string: (STOP to ending connection)\n\n");
do{
    while ((c = getchar ()) != '\n' && i < MAXLENGHT){
    buf[i++] = c;
}
buf[i] = '

I wrote this:

我写了这个:

Client:

printf("\nType a string: (STOP to ending connection)\n\n");
do{
    while ((c = getchar ()) != '\n' && i < MAXLENGHT){
    buf[i++] = c;
}
buf[i] = '\0';
len = strlen(buf);
}
while( strcmp(buf,"STOP")!=0);
close(sockfd);
exit(0);
}

Server:

int main (int argc, char **argv) {
int sock, fd;
socklen_t client_len;
struct sockaddr_in server, client;


if ((sock = socket (AF_INET, SOCK_STREAM, 0)) == -1) {
    perror ("Socket failed");
    exit (1);
}

server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons (SERVER_PORT);


if (bind ( sock, (struct sockaddr *) &server, sizeof server) == -1) {
    perror ("bind failed");
    exit (2);
}

listen (sock,1);


    while (1) {
    client_len = sizeof (client);
    if ((fd = accept ( sock, (struct sockaddr *) &client, &client_len)) < 0) {
        perror ("accepting connection");
        exit(3);
    }
    fprintf (stderr, "\nOpen.\n");
    send (fd, "\nWelcome!\n", 50, 0);
    check_stats (fd, fd);}

    close(fd);
    fprintf (stderr, "\nClose\n");
    exit (0);


 }  

.

void check_stats(int in, int out)

is a function where the server receives the string, do some things, and send it back to the client. My question is: In the server's code, what I have to put before

是服务器接收字符串,执行某些操作并将其发送回客户端的函数。我的问题是:在服务器的代码中,我必须提供的内容

close(fd)

that when user types "STOP", server ends, but before ending, it sends another BYE string to the client? I'm having problems with the

当用户键入“STOP”时,服务器结束,但在结束之前,它会向客户端发送另一个BYE字符串?我遇到了问题

recv(int sockfd, void *buf, size_t len, int flags);

function. What I have to put, in my main, as

功能。在我的主要内容中,我需要付出的代价

int sockfd

?

1 个解决方案

#1


0  

sockfd refers to the socket you are using to communicate with the server. https://linux.die.net/man/2/recv

sockfd指的是用于与服务器通信的套接字。 https://linux.die.net/man/2/recv

Here is the function prototype: ssize_t recv(int sockfd, void *buf, size_t len, int flags);

这是函数原型:ssize_t recv(int sockfd,void * buf,size_t len,int flags);

If you think about it, you will see that if you don't provide the function with the socket you are using, then how else will it know where to get the data?

如果您考虑一下,您会看到如果您没有使用您正在使用的套接字提供该功能,那么它将如何知道从何处获取数据?


'; len = strlen(buf); } while( strcmp(buf,"STOP")!=0); close(sockfd); exit(0); } printf("\nTy



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: