public class SendThread extends Thread {
private MainActivity activity;
Handler handler;
Socket s=null;
String message;
String ip; //远方服务器的IP地址
int port;//远方服务器的port
public SendThread(MainActivity activity,Handler handler,String ip, int port, String message){
this.activity = activity;
this.handler = handler;
this.message = message;
this.ip = ip;
this.port = port;
}
public void run(){
//向远方发起TCP连接
try {
s = new Socket(ip, port);
//第二个参数为True则为自动flush
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
s.getOutputStream())), true);
out.println(message);
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(activity,"发送成功",Toast.LENGTH_LONG).show();
}
});
} catch (Exception e1){
//e1.printStackTrace();
final String errMsg=e1.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(activity,"发送失败:"+errMsg,Toast.LENGTH_LONG).show();
}
});
}finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用:new SendThread(...).start;