我正在实现客户端/服务器文件发送和接收。
实现: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()函数后,服务器挂起或陷入无限循环,不再继续处理。我已经尝试使用 BufferedReader 和 readLine() 。出现错误“没有找到适合 BufferedReader(InputStream) 和 readLine() 的合适构造函数”,并发出警告。 除了 BufferedReader 还有其他选择吗?
最佳答案
readUTF()
读取 writeUTF()
写入的格式。您没有发送该内容,因此服务器无法读取它。使用 read(byte[])、
或 readFully()、
或 new BufferedReader(newInputStreamReader(in));
如果您使用readLine()
,您需要发送换行符。无论哪种情况,您都不需要发送尾随 null。
关于java - readUTF 在服务器端挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19826347/