【发布时间】:2015-06-05 20:48:05
【问题描述】:
我正在为学校开发一个程序,但遇到了一些套接字问题。我从下面的程序中粘贴了写入和读取命令,因为我认为这些是问题所在。程序应获取明文文件并使用提供的密钥对其进行加密。
我的问题:当我使用“client [plaintext] [key] [port]”执行程序时,程序返回“Reading data from client -- 140 bytes”然后就挂起。我可以按 ctrl-c 并且程序打印 ptext 和 ktext 的正确输出,并且 37 个字节被发送回客户端(这是正确的字节数)。我觉得加密的文本也应该打印,但它没有。
两个问题:
1) 程序为什么会挂起?
2) 为什么看起来像是从服务器向客户端写入数据,但客户端却没有读取任何数据?
提前感谢您提供的任何帮助。
客户
n = write(sockfd,ptext,strlen(ptext));
bzero(crypt_text, BUF_MAX);
bzero(buffer, BUF_MAX);
while((n = read(sockfd,buffer,BUF_MAX))>0){
printf("Reading data from Server -- %d bytes\n",n);
strcat(crypt_text, buffer);
bzero(buffer,BUF_MAX);
}
if (n < 0){
error("ERROR reading from socket");
}
printf("%s", crypt_text);
服务器
while((n = read(newsockfd,buffer,512))>0){
printf("Reading data from client -- %d bytes\n",n);
strcat(full_text, buffer);
bzero(buffer,BUF_MAX);
}
if (n < 0){
error("ERROR reading from socket");
}
bzero (ptext,BUF_MAX);
bzero (ktext, BUF_MAX);
strcpy(ptext, strtok(full_text,"["));
strcpy(ktext, strtok(NULL, "["));
printf("ptext length ==%s %d\n\n",ptext,strlen(ptext)); //Prints the correct plain text
printf("ktext length ==%s %d\n\n",ktext,strlen(ktext)); //prints the correct key
crypt_text = encrypt(ptext, ktext);
n = write(newsockfd,crypt_text,strlen(crypt_text));
printf("WRITE TO CILENT ==== %d",n); //This returns the correct number of bytes that should be sent back to client
if (n < 0){
error("ERROR writing to socket");
}
【问题讨论】:
-
你试过调试器吗? “为什么我的程序不起作用?”不鼓励在 SO 上提问。
-
回答 2) 您的程序正在将数据从服务器读取到缓冲区中,而不是直接读取到您的程序中。有一些选项可以“刷新”缓冲区并关闭缓冲。然后你可能会看到你的输出。
-
read()是阻塞 I/O 的一部分。 IIRC 你不能像那样使用read()。它总是会阻塞ie.keep等待客户端再次写东西