【发布时间】:2017-10-02 14:14:08
【问题描述】:
您好,提前致谢。
所以目前,我正试图让我的 TCP 程序从目录(这是服务器端)读取文件,然后将该文件发送到请求它的套接字(客户端)。
这是我的代码:
服务器端:
File FileList = new File(".....filepath....");
Scanner scan = new Scanner(FileList);
//idToFile just searching for the name of the file the client asked for
String TheName = idToFile(Integer.toString(result));
//Opens the chosen file such as an image to be used
File myImageFile = new File("....filepath...." + TheName);
//sendResponse is a function with a writeUTF (but only works for strings)
sendResponse("#OK");
sendResponse(TheName);
sendResponse(Long.toString(myImageFile.length()));
//This line causes the error and says that it expected a string and not a file
output.writeUTF(myImageFile);
private void sendResponse(String response)
{
try
{
output.writeUTF(response);
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
客户端:
ClientHandler client = new ClientHandler();
//getResponse just catches the written strings, but it can't work with a file either
String TheMessage = client.getResponse();
String Name = client.getResponse();
long FileSize = Long.parseLong(client.getResponse());
ClientHandler 的代码如下:
public class ClientHandler
{
private static int port = 2016;
private DataInputStream input;
private DataOutputStream output;
private Socket cSocket;
public ClientHandler()
{
cSocket = null;
try
{
cSocket = new Socket("localhost", port); //connecting to the server
System.out.println("Client is connected on port " + port);
output = new DataOutputStream(cSocket.getOutputStream());
input = new DataInputStream(cSocket.getInputStream());
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public void sendMessage(String message) //checking if the message is sent
{
try
{
output.writeUTF(message);
output.flush();
System.out.println("Message sent to the server");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public String getResponse()
{
String msg = "";
try
{
msg = input.readUTF();
}
catch(IOException ex)
{
ex.printStackTrace();
}
return msg;
}
}
那么我如何使用 DataOutputStream 将任何类型的文件从我的服务器发送到我的客户端,我的客户端如何使用 DataInputStream 捕获该文件并将其保存到磁盘?
谢谢。
【问题讨论】:
-
什么是
output?你能分享sendResponse的sn-p吗? -
这是什么?你在用什么?
sendResponseoutputclient??? -
我现在全部添加
-
刚刚添加了其他内容。我希望它足够了。
-
您可以考虑为此使用完善的协议,例如 HTTP。