我在Delphi中编写了一个简单的代码来发送和接收服务器和客户端之间的wav文件,它工作正常。我在android中编写了一个简单的代码,用于从服务器接收文件,但它不起作用。
以下是代码:
这是我在Delphi中的服务器代码:
procedure TfrmServer.TCPServerExecute(AThread: TIdPeerThread);
var
InputString:String;
FFilePath,AFullFileName:string;
AFileStream:TStream;
begin
FFilePath:='D:\pic1\';
InputString := AThread.Connection.ReadLn;
if InputString = 'WAV' then begin
Edit1.Text:=inttostr(strtoint(Edit1.Text)+1);
Edit2.Text:='connected';
AFullFileName := FFilePath + 'ad.wav';
AFileStream := TFileStream.Create(AFullFileName, fmOpenRead or fmShareDenyNone);
try
AThread.Connection.WriteStream(AFileStream, True, True);
// AThread.Connection.Write(UTF8Encode(TempStr));
finally
AFileStream.Free;
end;
end;
AThread.Connection.Disconnect;
end;
和delphi中的客户端代码工作正常:
procedure TForm2.Button1Click(Sender: TObject);
var
FFilePath:string;
AFileStream:TStream;
begin
if TCPClient.Connected then TCPClient.Disconnect;
TCPClient.Host := '127.0.0.1';
TCPClient.Port := 8090;
FFilePath:='.\';
if FileExists(FFilePath + '1.wav') then
DeleteFile(FFilePath + '1.wav');
AFileStream := TFileStream.Create(FFilePath + '1.wav', fmCreate);
try
try
TCPClient.Connect;
try
TCPClient.WriteLn('PIC');
TCPClient.ReadStream(AFileStream, -1, False);
finally
TCPClient.Disconnect;
end;
finally
AFileStream.Free;
end;
except
DeleteFile(FFilePath + '1.wav');
end;
end;
这是我的Android Java代码:
final Button send = (Button) findViewById(R.id.bSend);
final TextView status = (TextView) findViewById(R.id.tvStatus);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Socket s = null;
// BufferedInputStream get = null;
try {
s = new Socket("192.168.1.2", 8090);
status.setText("74");
get = new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-"));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8")), true);
if (out != null && !out.checkError()) {
out.println("WAV");
out.flush();
}
// receive file
// byte[] mybytearray = new byte[1024];
String SS = "";
System.out.println("84");
String dir = Environment.getExternalStorageDirectory().toString() + "/" + "Aidin";
File path = new File(dir);
File root = new File(path, "ad.wav");
FileOutputStream fos = new FileOutputStream(root); // destination path and name of file
BufferedOutputStream bos = new BufferedOutputStream(fos);
System.out.println("92");
bos=get.read();
bos.flush();
long end = System.currentTimeMillis();
Toast.makeText(getApplicationContext(), "File received", Toast.LENGTH_SHORT).show();
// System.out.println(end-start);
bos.close();
fos.flush();
s.close();
fos.close();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Errorr", Toast.LENGTH_SHORT).show();
// System.exit(0);
}
}
private void Log(String string, String string2) {
// TODO Auto-generated method stub
}
});