1

I am doing a Unix, C assignment. I am creating a Server and a Client which will interact with each other. I am pretty sure I have set up the basic framework but I when I try to send/receive messages, it doesn't work.

Here is the while loop code for the server, I tried to show only the relevant code:

while(1) {
            clntAdrLen = sizeof(clntAddr);
            clntFd = accept(srvrFd, (struct sockaddr*)&clntAddr, NULL);
            if (fork() == 0) { 
                    send(clntFd, "YourMessage", 12, NULL);
                    close(clntFd);
                    exit(0);
            } else {
                    close(clntFd);
            }
}

And here is the code for client:

do {
            result = connect(srvrFd, (struct sockaddr*)&srvrAddr, srvrLen);
            if(result==-1) {
                    sleep(1);
            }
            recv(srvrFd, buf, sizeof(buf), NULL);
            printf("%s", buf); //here I try to print the message sent by server
    } while (result==1);

When I run both server and client, It should print "YourMessage". Instead it prints:

N0�,

Am I just doing it wrong? Thanks

4

2 回答 2

1

我猜你的问题出在接受功能上。

正如 Linux 程序员手册中所说:

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

addrlen 参数是一个值结果参数:调用者必须将其初始化为包含 addr 指向的结构的大小(以字节为单位);返回时它将包含对等地址的实际大小。

于 2013-05-20T03:50:48.883 回答
-1

帮自己一个忙,给自己买《UNIX网络编程》ISBN-10:0139498761

套接字编程的方式远比表面上看到的要多。

一方面,您如何在接收端知道发送的字符串有多长?您是否会假定它始终是 12,在大多数实际示例中,它不会每次都相同。

你是要一直读到字符串的结尾,还是要在开头发送一个整数来告诉读者长度是多少?

如果您使用整数,您知道字节序吗?

如果我们为你做作业,你真的会学到什么吗?大概你在上大学并支付学费。你是来通过的还是来学习的?

于 2013-05-20T03:46:42.293 回答