こんにちは、ありがとうございます。Java TCP - DataOutputStreamを使用してファイルを送信
現在、私は自分の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;
}
}
だから、どのようにすることができます私はDataOutpを使うutStreamを使用して、サーバーからクライアントにファイルを送信し、クライアントがDataInputStreamを使用してファイルをキャッチしてディスクに保存する方法を教えてください。
ありがとうございます。
「出力」とは何ですか? 'sendResponse'のスニペットを共有できますか? – Archit
これは何ですか?あなたは何を使っていますか? 'sendResponse''出力 ''クライアント '??? – Oleg
私は今それらをすべて追加します – Duckman