我正在实现客户端/服务器文件的发送和接收。

实现:C语言中的客户端和Java语言中的服务器。

发送的部分C代码:

long count;
FILE *file;
char *file_data;

file=fopen("test.txt","rb");
fseek (file , 0 , SEEK_END);
count = ftell (file);
rewind (file);

file_data=(char*)malloc(sizeof(char)*count);
fread(file_data,1,count+1,file);
fclose(file);

if ((numbytes = send(sockfd, file_data, strlen(file_data)+1 , 0)) == -1)
{
 perror("client: send");
 exit(1);
}


Java代码接收的一部分:

public String receiveFile()
{
   String fileName="";
   try
   {
    int bytesRead;
    InputStream in = clientSocket.getInputStream();
    DataInputStream clientData = new DataInputStream(in);
    fileName=clientData.readUTF();
   }
}


使用readUTF()函数后,服务器挂起或处于无限循环中,并且不再继续。我已经尝试过用readLine()进行BufferedReader。有一个错误,即“没有为BufferedReader(InputStream)和readLine()找到合适的构造函数给出警告。
除了BufferedReader之外,还有其他选择吗?

最佳答案

readUTF()读取writeUTF()编写的格式。您没有发送该消息,因此服务器无法读取它。使用read(byte[]),readFully(),new BufferedReader(newInputStreamReader(in));

如果使用readLine(),则需要发送换行符。无论哪种情况,您都无需发送结尾的null。

10-04 23:00
查看更多