私は、クライアントからサーバーへ、またはその逆にファイルをコピーする単純なクライアントサーバーアプリケーションを実行しています。もちろん、私はソケットを使用しています。アプリには、選択できるいくつかのオプションを含むクライアントメニューが表示されます。1。サーバーでコピーを作成します。2。サーバーなどからfileCopyを取得します。
問題は、最初のオプションを選択したときに、2番目のオプションを選択できないことです。この例外について読みましたが、この問題を解決する方法がわかりません。私はあなたのアイデアを楽しみにしています。
クライアントサイドコードの一部があります:
public Client(String host, int port) {
try {
s = new Socket(host, port);
System.out.println("Witaj w programie");
boolean finished = false;
Scanner sc = new Scanner(System.in);
while(!finished){
System.out.println("\n\n1.Zrob kopie zapasowa pliku");
System.out.println("2. Przywroc kopie");
System.out.println("0.Zakoncz");
char c = sc.nextLine().charAt(0);
switch(c){
case '1':
this.sendMessage(1);
makeCopy(s);
//s.close();
break; ...
sendMessageメソッドコード:
public void sendMessage(int message_id) throws IOException{
oos = new ObjectOutputStream(s.getOutputStream());
ois = new ObjectInputStream(s.getInputStream());
oos.writeInt(message_id);
oos.flush();
}
およびmakeCopyメソッドコード:
private void makeCopy(Socket clientSock) throws IOException {
File file = new File("D:\\klient\\doKopii.bmp");
DataOutputStream dos = new DataOutputStream(clientSock.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
fis.close();
dos.close();
}
サーバーコードからコピーをダウンロードします。
private void saveFile(Socket clientSock) throws IOException {
//DataInputStream dis = new DataInputStream(clientSock.getInputStream());
FileOutputStream fos = new FileOutputStream("D:\\klient\\przywroconaKopia.bmp");
File zSerwera = new File("D:\\serwer\\kopiaPliku.bmp");
byte[] buffer = new byte[4096];
int filesize = (int)zSerwera.length();
int read = 0;
int totalRead = 0;
int remaining = filesize;
while((read = ois.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
//fos.close();
//ois.close();
}
DataOutputStreamが閉じているため、これが機能しないことを認識しています。これは、ソケットも閉じていることを意味します。この行を削除しましたが、1つのオプションを選択してから2番目のオプションを選択した後(最初のオプションが完了したとき)、アプリケーションがフリーズします。
oos = new ObjectOutputStream(s.getOutputStream());
ois = new ObjectInputStream(s.getInputStream());
public void sendMessage(int message_id) throws IOException{
oos.writeInt(message_id);
}
makeoos
とois
asインスタンス変数を作成し、それらが1回だけインスタンス化されることを確認します。データ出力ストリームを個別に取得する必要がある理由同じobjectoutputstreamでバイト配列を送信できます
private void makeCopy(Socket clientSock) throws IOException {
File file = new File("D:\\klient\\doKopii.bmp");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
while (fis.read(buffer) > 0) {
oos.write(buffer);
}
}
これはあまり良いコーディング慣行ではありませんが、多分あなたはこのアプローチを試してみるべきです
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加