老师,我把客户端的代码放在android程序里,给一个button监听事件,就是调用这个socket方法,但是一点button就闪退了,没连接上~
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
btn=(Button) findViewById(R.id.button2);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
initClientSocket();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void initClientSocket() {
try {
Socket socket=new Socket("192.168.191.1",8888);
OutputStream os=socket.getOutputStream();
PrintWriter pw=new PrintWriter(os);
pw.write("nihao");
pw.flush();
socket.shutdownOutput();
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}