} public void setRunning(boolean rr){ this.isrunning=rr; } } 5、TCP数据监听接口: package sunstudio.netlib;
public interface TcpDataListener{ public void onTcpDataArrived(TcpDataEvent evt); } 6、TCP数据包接收事件: package sunstudio.netlib;
import java.net.*;
public class TcpDataEvent{ byte[] head=null; int datalen=-1; byte[] datas=null; public TcpDataEvent(byte[] h,int len,byte[] dt){ head=h; datalen=len; datas=dt; } public byte[] getHeader(){ return head; } public byte[] getData(){ return datas; } public int getDataLen(){ return datalen; } } 7、TCP数据发送器: package sunstudio.netlib;
import java.io.*; import sunstudio.util.*;
public class TcpDataSender{ OutputStream os; byte[] d=new byte[1024]; int l; public TcpDataSender(OutputStream ost){ os=ost; } public void sendLoginBack(int userID){ byte[] cd=new byte[9]; System.arraycopy(Convert.intToBytes(userID),0,cd,2,4); sendeHeader((byte)10,cd); } public void sendeHeader(byte cmdType,byte[] cData){ try{ d[0]=cmdType;//登录 System.arraycopy(Convert.shortToBytes((short)0),0,d,1,2); System.arraycopy(cData,0,d,3,9); os.write(d,0,12); os.flush(); }catch(Exception e){} } public void sendUserListData(byte[] ud){ byte[] hh=new byte[12]; hh[0]=6; System.arraycopy(Convert.shortToBytes((short)ud.length),0,hh,1,2); sendData(hh,ud,ud.length); } public void sendData(byte[] hh,byte[] dd,int ln){ try{ os.write(hh); os.write(dd,0,ln); }catch(Exception e){} } } 8、数据接收类(保证读取TCP字节数组数据长度正确) package sunstudio.util;
import java.io.*;
public class HttpInputStream extends InputStream{ InputStream is=null; public HttpInputStream(InputStream is1){ is=is1; } public int read() throws IOException{ return is.read(); } public String readLine() throws IOException{ ByteArrayOutputStream b=new ByteArrayOutputStream(); int c; while((c=read())!=-1){ if(c==10)break; else b.write(c); } if(c==-1)return null; if(b.size()==1){ if(b.toByteArray()[0]==13)return ""; } return new String(b.toByteArray(),0,b.size()-1); } public static void readBytes(InputStream inputStream,int length,byte[] data) throws IOException{ if(length==0)return; int上一页 [1] [2] [3] [4] [5] 下一页
|