我正试图通过局域网将文件从我的PC发送到我的Android手机。
客户(发件人,PC):
public class Client {
public static void main(String[] args) {
String host = "192.168.0.108"; //IP of phone (I know, hardcoding is evil...)
int port = 19999;
String TimeStamp;
Socket con;
File f = new File("/home/sebastian/test");
try {
InetAddress address = InetAddress.getByName(host);
con = new Socket(address, port);
} catch (IOException e) {
e.printStackTrace();
return;
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(f));
BufferedOutputStream bos = new BufferedOutputStream(con.getOutputStream());
int i;
System.out.println("Starting transmission");
while ((i = fis.read()) != -1) {
bos.write(i);
}
System.out.println("Finished");
bos.flush();
fis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}}
});
t.start();
}
}
服务器(接收器,电话):
class Server extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startserver();
}
private void startserver() {
try {
socketl = new ServerSocket(port, 0, InetAddress.getByName("192.168.0.108"));
Thread t = new Thread (new Runnable() {
@SuppressLint("SdCardPath")
@Override
public void run() {
while (true) {
try {
connection = socketl.accept();
BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
instr = new StringBuffer();
int i;
File f = new File("/sdcard/jaisb/streamtest");
f.delete();
f.createNewFile();
Log.d("log", "file created");
FileOutputStream fos = new FileOutputStream(f);
while ((i = isr.read()) != -1) {
fos.write(i);
}
Log.d("log", "file written");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
}
如果我在我的homedir中创建一个名为test
的文本文件,那就很好了,文件到达没有错误......但是,如果我用其他媒体替换文本(即图片和音乐(我试过了) JPG和MP3)),文件已损坏。
将它们与 hexedit 中的原始文件进行比较,我注意到在发送音乐文件时,问题是某些字节丢失了;文件的前几个字节是好的,但后来它开始丢失字节......
发送JPG时,大多数字节都是错误的。即使前四个字节也从FF D8 FF E0
更改为FD FD FD FD
。
我做错了什么?如何通过本地网络发送非文本文件?