客户端 - 服务器程序 [英] client-server programme
问题描述
我们已经在UNIX环境中进行简单的 client.c
和 server.c
程序。我们正在使用它首先打开它,然后阅读它,并使用发送打开
,读
传输一个简单的文本文件,和发送
系统调用;在客户端我收到它,并通过创建服务器计算机上的文件写它。转移正在发生相当顺利,但是在客户端收到的文件是不完全在服务器端的相同。在可读字符之间有一些不可读的字符。能否请你告诉我什么可能是这种情况的可能的原因?虽然该文件的大部分是相同的,只是在之间的一小部分有一定的差异。
code可以看出这里。
谢谢!
服务器端循环:
做
{
N =读取(T,BUF,100);
写(1,BUF,strlen的(BUF));
送(连接,BUF,strlen的(BUF),0);
}而(N!= 0);
在客户端
做
{
bytes_recieved =的recv(袜子,recv_data,100,0);
数=写(T,recv_data,strlen的(recv_data));
}而(bytes_recieved!= 0);
在一审中,不要使用的strlen()
。但绝对没有保证,还会有文件流中的NULL字节的任何地方,而事实上有一个文本文件中从未有应。
环路周围的每一次你应该输出已接收的实际字节数,而不是有多少的strlen()
认为可能在缓冲区:
做
{
bytes_received =的recv(袜子,recv_data,100,0);
如果(bytes_received℃,){
PERROR(读);
打破;
}否则如果(bytes_received == 0){
打破;
}其他{
数=写(T,recv_data,bytes_received);
//在理论上 - 在这里添加错误检查呢!
}
}而(计数大于0);
We have made simple client.c
and server.c
programme in an UNIX environment. We are using it transfer a simple text file by first opening it, then reading it and sending using open
, read
, and send
system calls; on client side I am receiving it, and writing it by creating a file on server machine. The transfer is taking place quite smoothly but the file recieved at the client side is not exactly the same on the server side. In between the readable characters there are some unreadable characters. Can you please tell me what could be the possible reason for this? Though the most part of the file is same, only a small part in between has some discrepancies.
Code can be seen here.
Thanks!
server side loop:
do
{
n=read(t,buf,100);
write(1,buf,strlen(buf));
send(connected, buf,strlen(buf), 0);
} while(n!=0);
on client side
do
{
bytes_recieved=recv(sock,recv_data,100,0);
count=write(t,recv_data,strlen(recv_data));
} while(bytes_recieved!=0);
In the first instance, don't use strlen()
. There's absolutely no guarantee that there'll be a NUL byte anywhere in the file stream, and in fact with a text file there never should be.
Each time around the loop you should output the actual number of bytes that were received, not how many strlen()
thinks might be in the buffer:
do
{
bytes_received = recv(sock, recv_data, 100, 0);
if (bytes_received < 0) {
perror("read");
break;
} else if (bytes_received == 0) {
break;
} else {
count = write(t, recv_data, bytes_received);
// in theory - add error check here too!
}
} while (count > 0);
这篇关于客户端 - 服务器程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!