package com.example.sharefileapp;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Vibrator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends Activity {
private EditText tv_ip = null;
private TextView tv_showmes = null;
private EditText ed_msg = null;
private Button btn_send = null;
private static final int PORT = 8192;
private static final int SERVERPORT = 8192; // listen port
private static final String path = "/mnt/sdcard/";
private static final String FILE = "sendfile";
//private static final int MESSAGE = 0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     // init client;
      tv_ip = (EditText) findViewById(R.id.et_ip);
      tv_showmes = (TextView) findViewById(R.id.tv_mes_show);
      ed_msg = (EditText) findViewById(R.id.et_mes);
      btn_send = (Button) findViewById(R.id.btn_send);
     
new Thread(new Service()).start(); btn_send.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new SendMessage()).start();
showToast("启动线程");
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
long[] pattern = { 100, 50, 100, 50, 100, 50, 100, 50 }; // OFF/ON/OFF/ON...
vibrator.vibrate(pattern, -1);
}
});
    }
public Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle b = msg.getData();
String mesg = b.getString("mes");
tv_showmes.setText(tv_showmes.getText().toString() + mesg + "\n");
}
};
class SendMessage implements Runnable{
private BufferedOutputStream bufferedOutputStream = null;
private BufferedInputStream bufferedInputStream = null;
@Override
public void run() {
Looper.prepare();
try {
showToast("启动线程");
String chathost = tv_ip.getText().toString().trim();
Socket socket = new Socket(chathost, PORT);
String msg = ed_msg.getText().toString();
byte[] buffer = new byte[1024];
bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
bufferedInputStream = new BufferedInputStream(socket.getInputStream());
bufferedOutputStream.write(msg.getBytes("UTF-8"));
bufferedOutputStream.flush();
showToast("开始发送");

File file = new File(path, msg);
FileInputStream fileInputStream = new FileInputStream(file);
int len = fileInputStream.read(buffer);
while(len!=-1){
bufferedOutputStream.write(buffer,0,len);
bufferedOutputStream.flush();
len = fileInputStream.read(buffer);
}
if(fileInputStream!=null){
fileInputStream.close();
fileInputStream = null;
showToast("发送成功");
}


} catch (UnknownHostException e) {
ShowDialog("未知的主机名");
e.printStackTrace();
} catch (IOException e) {
ShowDialog("异常了");
e.printStackTrace();

}

}
public void ShowDialog(String msg) {
new AlertDialog.Builder(this).setTitle("notification").setMessage(msg)
.setPositiveButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub }
}).show();
} class Service implements Runnable {
private Socket socket;
private BufferedInputStream in = null;
private BufferedOutputStream out = null;
private String msg = "";
private ServerSocket server = null;
private File file = null;
private FileOutputStream fileOutputStream = null;
public void run() {
Looper.prepare();
try {
server = new ServerSocket(SERVERPORT);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {
socket = server.accept();
in = new BufferedInputStream(
socket.getInputStream());
out = new BufferedOutputStream(socket.getOutputStream());
byte[] buffer = new byte[1024];
in.read(buffer);
msg = new String(buffer,"UTF-8");
file = new File(path, msg);
fileOutputStream = new FileOutputStream(file);

int len = in.read(buffer);
while(len!=-1){
fileOutputStream.write(buffer,0,len);
len = in.read(buffer);
}
if(fileOutputStream!=null){
fileOutputStream.close();
fileOutputStream = null;

}
// notice the UI thread to refactor the ui
Message message = new Message();
Bundle b = new Bundle();
b.putString("mes", msg+socket.getInetAddress().toString());
message.setData(b);
MainActivity.this.mHandler.sendMessage(message); } catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void showToast(String s){
Toast.makeText(this, s, 1).show();
}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="192.168.1.102"
        android:id="@+id/et_ip"
        />
   
<EditText 
    android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Remember.mp3"
        android:id="@+id/et_mes"
    />
<Button 
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送"
        android:id="@+id/btn_send"
    />
 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_mes_show"
        />
</LinearLayout>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sharefileapp"
    android:versionCode="1"
    android:versionName="1.0" >    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
没有报错,可是传不了文件,一直停在activity界面上,求大神指出其中错误!

解决方案 »

  1.   

    socket连接,你实现了客户端,但另一端的服务器端(另一个手机)没有建立socket服务器,没有进行监听,即使创建了客户端的socket,服务器端也没响应啊~~所以socket就没建立起来
    String chathost = tv_ip.getText().toString().trim();
    Socket socket = new Socket(chathost, PORT);
      

  2.   

    不是呀,我在service里面已经实现了服务器端的监听了,也就是每个手机都有一个socket和一个serversocket,不应该是这里有问题
      

  3.   


    1检查俩手机是否在一个网段
    2在作为服务器的手机上toast一下连接成功的客户端ip.
      

  4.   


    用wifi连的,在同一局域网下,服务端也能获取到客户端ip呀,发送线程只能执行到启动线程那个toast,估计是获取socket流那里阻塞了吧。。自己也不是很清楚