80,490
社区成员
发帖
与我相关
我的任务
分享
public class MainActivity extends Activity {
private EditText ed_tex;
private Button btn_sent;
private int SERVER_POINT = 2041;
private String SERVER_ADDRESS = "192.168.18.127";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
// TODO Auto-generated method stub
ed_tex = (EditText) findViewById(R.id.ed_text);
btn_sent = (Button) findViewById(R.id.btn_sent);
btn_sent.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
byte[] str= ed_tex.getText().toString().getBytes();//截取输入字符串中的数值变成二进制
if (v != null && !str.equals("")) {
System.out.println("准备发送....");
new SendThred(str).start();
}
}
});
}
class SendThred extends Thread implements Runnable {
byte[] Str_message;
public SendThred(byte[] str){
this.Str_message = str;//自定义线程发送输入字节
}
public void run() {
try {
System.out.println("正在连接服务器...");
Socket s = new Socket(SERVER_ADDRESS, SERVER_POINT);
System.out.println("成功连接服务器...");
System.out.println("准备发送数据...");
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.write(Str_message);
System.out.println("成功发送数据...");
System.out.println("准备接收服务器返回结果...");
DataInputStream is = new DataInputStream(s.getInputStream());
System.out.println("成功接收服务器返回数据:" + is.readUTF());
//System.out.println("成功接收服务器返回数据:" + is.read());
Toast.makeText(getApplicationContext(), "成功接收服务器返回数据:" + is.readUTF(), Toast.LENGTH_SHORT).show();
is.close();
out.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}