Android客户端Socket抛出SocketException:

时间:2011-11-11 19:49:11

标签: java android

我正在尝试在android中实现java socket客户端,而我的服务器是我的笔记本电脑。我希望我的android手机通过java socket连接到笔记本电脑。但我在客户端获得异​​常:“SocketException”,它看起来因为socket()调用无法正确创建套接字。下面是我的Android客户端代码供审阅。有没有解决异常的解决方案:

public class SimpleActivityExampleActivity extends Activity  {

/** Called when the activity is first created. */
private String usrName;
private String vendorName;
private String message;
public Socket socket;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }


public void submitTheForm(View view) {

    final EditText edittext1 = (EditText) findViewById(R.id.editText1);
    final EditText edittext2 = (EditText) findViewById(R.id.EditText01);
    final EditText edittext3 = (EditText) findViewById(R.id.editText2);
    usrName = edittext1.getText().toString(); 
    vendorName = edittext2.getText().toString();
    message = edittext3.getText().toString();
    message = usrName+ "," + vendorName + "," + message;

    byte[] msg = message.getBytes();
    try {
    InetAddress serverAddr = InetAddress.getByName("192.168.1.2");
        Log.d("ClientActivity", "C: Connecting...");

        socket = new Socket(serverAddr, 2200);
    socket.getOutputStream().write(msg);
    socket.getOutputStream().flush();
    } catch (UnknownHostException e) {

        Toast.makeText(SimpleActivityExampleActivity.this, "unknownhostException", Toast.LENGTH_SHORT).show();
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SocketException e) {
        // TODO Auto-generated catch block

        Toast.makeText(SimpleActivityExampleActivity.this, "Sockexception", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }catch (IOException e) {
        // TODO Auto-generated catch block
        //System.out.println("in IOexception for sure");
        Toast.makeText(SimpleActivityExampleActivity.this, "IOexception", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
    catch (Exception e){
        Toast.makeText(SimpleActivityExampleActivity.this, "Exception", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }finally {
        if(socket != null){
            try {
                socket.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
} 

从main.xml文件“android:onClick =”submitTheForm“

按钮上调用submitTheForm()函数

2 个答案:

答案 0 :(得分:0)

您是否可能忘记将Internet权限添加到清单文件中?

<uses-permission android:name="android.permission.INTERNET" />

答案 1 :(得分:0)

您是否设置了

<uses-permission android:name="android.permission.INTERNET" />

许可?

找到此here