ull; public ChessUser(String un,int ui,Socket st){ username=un; userID=ui; socket=st; System.arraycopy(username.getBytes(),0,data,0,Math.min(8,username.getBytes().length)); System.arraycopy(Convert.intToBytes(ui),0,data,8,4); data[12]=(byte)-1; data[13]=(byte)-1; } public boolean init(){ try{ sender=new TcpDataSender(socket.getOutputStream()); receiver=new TcpDataReceiver(socket.getInputStream()); receiver.addTcpDataListener(this); return true; }catch(IOException e){} return false; } public void setState(int stat){ state=stat; data[13]=(byte)stat; } public void start(){ try{ sender.sendLoginBack(userID); receiver.start(); }catch(Exception e){} } public void onTcpDataArrived(TcpDataEvent evt){ ChessServer.hwnd.onUserPackageArrived(evt.getHeader(),evt.getDataLen(),evt.getData()); } public byte[] getBytes(){ return data; } public void close(){ try{ if(socket!=null){ socket.close(); socket=null; } }catch(Exception e){} try{ if(receiver!=null){ receiver.setRunning(false); receiver=null; } }catch(Exception e){} try{ if(sender!=null)sender=null; }catch(Exception e){} } } 4、TCP数据接收器: package sunstudio.netlib;
import java.util.*; import java.net.*; import java.io.*; import sunstudio.util.*;
public class TcpDataReceiver extends Thread{ Vector listeners=new Vector(); boolean isrunning=true; InputStream is=null; byte[] h=new byte[12]; byte[] d=new byte[1024]; int l=0; public TcpDataReceiver(InputStream s){ is=s; } public void run(){ try{ while(isrunning){ HttpInputStream.readBytes(is,12,h); l=Convert.byteToShort(h[1],h[2]); if(l>0)HttpInputStream.readBytes(is,l,d); if(l>0)notifyListeners(h,l,d); else if(l==0)notifyListeners(h,0,null); else throw new IOException(); } }catch(IOException e){ System.out.println("读取流数据异常!"); //异常处理,关闭socket } } public void addTcpDataListener(TcpDataListener hrl){ listeners.addElement(hrl); } synchronized void notifyListeners(byte[] hh,int ll,byte[] dd){ TcpDataEvent evt=new TcpDataEvent(hh,ll,dd); for(Enumeration enumeration=listeners.elements();enumeration.hasMoreElements();((TcpDataListener)enumeration.nextElement()).onTcpDataArrived(evt)); 上一页 [1] [2] [3] [4] [5] 下一页
|