0

我正在尝试通过 LAN 进行语音呼叫应用程序,首先我尝试发送简单的文本消息以使套接字正常工作,但是当我按下发送按钮时,应用程序关闭。

主要活动

 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.net.InetAddress;
 import java.net.ServerSocket;
 import java.net.Socket;
 import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.List;





 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiManager;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.app.Activity;
 import android.app.ProgressDialog;
 import android.content.Context;
 import android.content.Intent;
 import android.text.format.Formatter;
 import android.util.Log;
 import android.view.Menu;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;
 import android.widget.Toast;

 public class MainActivity extends Activity {
String IP;
TextView tv;
ServerSocket ss = null;
   String mClientMsg = "";
   Thread myCommsThread = null;
   protected static final int MSG_ID = 0x1337;
   public static final int SERVERPORT = 6000;
   private Socket socket;
   private String serverIpAddress = "192.168.1.101";
   private static final int REDIRECTED_SERVERPORT = 5000;
   Button bt;
   TextView tv2;

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.textView1);
tv2  = (TextView) findViewById(R.id.textView3);

    bt = (Button) findViewById(R.id.button1);
    ShowIp();
     TextView tv1 = (TextView) findViewById(R.id.textView2);
        tv1.setText("Nothing from client yet");
        this.myCommsThread = new Thread(new CommsThread());
        this.myCommsThread.start();

        bt.setOnClickListener(new OnClickListener() {
             public void onClick(View v) {

                 startActivity(new Intent(MainActivity.this,      MakeCall.class));

             }      
          });




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void ShowIp(){

    WifiManager wim= (WifiManager) getSystemService(WIFI_SERVICE);
    List<WifiConfiguration> l = wim.getConfiguredNetworks();

    WifiConfiguration wc =new WifiConfiguration();

    IP=Formatter.formatIpAddress(wim.getConnectionInfo().getIpAddress());
    tv.setText(IP);

}

@Override
   protected void onStop() {
    super.onStop();
    try {
        // make sure you close the socket upon exiting
        ss.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
   }

   Handler myUpdateHandler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case MSG_ID:
            TextView tv1 = (TextView) findViewById(R.id.textView2);
            tv1.setText(mClientMsg);
            break;
        default:
            break;
        }
        super.handleMessage(msg);
    }
   };
   class CommsThread implements Runnable {
    public void run() {
        Socket s = null;
        try {
            ss = new ServerSocket(SERVERPORT );
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {
            Message m = new Message();
            m.what = MSG_ID;
            try {
                if (s == null)
                    s = ss.accept();
                BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String st = null;
                st = input.readLine();
                mClientMsg = st;
                myUpdateHandler.sendMessage(m);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }

 }

MakeCall 活动

       private Button bt;
   private TextView tv;
   private Socket socket;
   private String serverIpAddress = "192.168.2.11";
   private static final int REDIRECTED_SERVERPORT = 5000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.makecall);

      bt = (Button) findViewById(R.id.button1);
      tv = (TextView) findViewById(R.id.textView1);

      bt.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
             try {
                 InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                 socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
              } catch (UnknownHostException e1) {
                 e1.printStackTrace();
              } catch (IOException e1) {
                 e1.printStackTrace();
              }

            try {
               EditText et = (EditText) findViewById(R.id.editText1);
               String str = et.getText().toString();
               PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
               out.println(str);
               Log.d("Client", "Client sent message");
            } catch (UnknownHostException e) {
               tv.setText("Error1");
               e.printStackTrace();
            } catch (IOException e) {
               tv.setText("Error2");
               e.printStackTrace();
            } catch (Exception e) {
               tv.setText("Error3");
               e.printStackTrace();
            }
         }
      });
}

 }

清单文件

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.socketcalldemo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.socketcalldemo.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.example.socketcalldemo.MakeCall"
              android:label="Make Free Calls" />
     </application>

  </manifest>

日志猫

06-20 16:14:19.626: W/System.err(331): java.net.SocketException: 套接字已关闭 06-20 16:14:19.646: W/System.err(331): 在 java.net。 ServerSocket.checkClosedAndCreate(ServerSocket.java:441) 06-20 16:14:19.646: W/System.err(331): at java.net.ServerSocket.accept(ServerSocket.java:143) 06-20 16:14: 19.646: W/System.err(331): 在 com.example.socketcalldemo.MainActivity$CommsThread.run(MainActivity.java:138) 06-20 16:14:19.646: W/System.err(331): 在 java .lang.Thread.run(Thread.java:1019) 06-20 16:14:19.646: W/System.err(331): java.net.SocketException: 套接字已关闭 06-20 16:14:19.646: W /System.err(331): at java.net.ServerSocket.checkClosedAndCreate(ServerSocket.java:441) 06-20 16:14:19.646: W/System.err(331): at java.net.ServerSocket.accept( ServerSocket.java:143) 06-20 16:14:19.646: W/System.err(331): at com.example.socketcalldemo。MainActivity$CommsThread.run(MainActivity.java:138) 06-20 16:14:19.646: W/System.err(331): 在 java.lang.Thread.run(Thread.java:1019)

4

0 回答 0