看了一下之前的代码,发现自己好白痴,这么简单的问题弄的这么麻烦。思路就像上一篇博客那样说的,一点都没错。一开始做出来那货写了一大堆没用的东西。另外在rec里面网关弄错了,不过这货本来是下一步要实现的自己设的固定IP,所以这错就无关紧要了,改一下就行了。
package com.example.reciver;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
final private String uploadFile = Environment.getExternalStorageDirectory() + "/finger/myPic.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread()
{
@Override
public void run()
{
try
{
Socket s = new Socket("192.168.43.1" ,30000);
InputStream fis = s.getInputStream();
FileOutputStream fos = new FileOutputStream (uploadFile);
int hasRead = 0;
byte[] buf = new byte[1024];
while ((hasRead = fis.read(buf))>0)
{
fos.write(buf ,0, hasRead);
}
fis.close();
fos.close();
s.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
}
}
上面是接收方的代码,下面是发送方的代码
package com.example.sender;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button sendMsg;
final private String uploadFile = Environment.getExternalStorageDirectory() + "/finger/myPic.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendMsg = (Button)this.findViewById(R.id.sendMsg);
sendMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SocketSendMsg();
}
});
}
private void SocketSendMsg()
{
new Thread()
{
@Override
public void run()
{
try
{
ServerSocket ss = new ServerSocket(30000);
while(true)
{
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
FileInputStream fis =new FileInputStream(uploadFile);
byte[] buf = new byte[1024];
int hasRead = 0;
while ((hasRead = fis.read(buf)) > 0 )
{
os.write(buf ,0,hasRead);
}
os.close();
fis.close();
s.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
}
}