62,616
社区成员
发帖
与我相关
我的任务
分享
class TF extends Thread
{
public static SClient t[];
public static int maxthread=10;
public TF()
{
this.init();
}
public void init(){
t=new SClient[maxthread];
}
public void run()
{
int i =0;
for(i=0;i<t.length;i++){
t[i]=new SClient();
t[i].start();
System.out.println("thread-"+t[i].getId()+": building... ");
}
int dc[] = new int[maxthread];
while(true){
for(i=0;i<t.length;i++){
if(t[i].isAlive()==true && t[i].isExit()==false && t[i].isEnd()==false ){
dc[i]=0;
}else if(t[i].isAlive()==false){
dc[i]++;
System.out.println(" thread-"+t[i].getId()+": OffLine! Start trying again... count="+dc[i]);
t[i]=new SClient();
t[i].start();
}
waiting(100);
}
waiting(1000);
}
}
public void waiting(Integer sec){
try{
TF.sleep(sec);
}catch(Exception e){
}
}
}
class SClient extends Thread {
private Socket sock = new Socket();
private InputStream in=null;
private OutputStream out=null;
private InputStreamReader isr = null;
private BufferedReader br = null;
private int port = 80;
private String host ="127.0.0.1";
private boolean _exit=false;
private boolean _end=false;
public void run(){
SocketAddress addr = new InetSocketAddress(this.host, this.port);
try{
sock.connect(addr, 3000);
this.in = sock.getInputStream();
this.out = sock.getOutputStream();
this.br = new BufferedReader(new InputStreamReader(this.in,"utf-8"));
System.out.println("thread-"+this.getId()+" connect ok");
}catch(Exception e){
this._exit=true;
System.out.println("thread-"+this.getId()+" connect error");
}
while(this._exit==false){
try{
System.out.println("thread-"+this.getId()+" "+(new Date() ) );
this.send();
}catch(IOException e){
this._exit=true;
System.out.println("thread-"+this.getId()+" IO error");
}catch(Exception e){
this._exit=true;
e.printStackTrace();
}
waiting(100);
}
System.out.println("thread-"+this.getId()+" close");
this.close();
this._end=true;
}
public void close(){
try {
this.sock.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void send() throws Exception,IOException {
String msg = "send msg...end";
this.out.write(msg.getBytes("UTF-8"));
this.out.flush();
msg = null;
}
public void waiting(Integer sec){
try{
SClient.sleep(sec);
}catch(Exception e){
}
}
public boolean isExit(){
return this._exit;
}
public boolean isEnd(){
return this._end;
}
}