前段时间写了个web端与C服务端之间的通信不过用的是短连接 非堵塞的方式,一直想使用长连接,使tomcat启动的时候就和C服务端进行通信,但是一直没找到方法希望je的朋友能给点思路。先来看我现在的具体实现
通信的核心类
public
class
newsSockBase
{
private
SocketChannel sc;
private
final
int
MAX_LENGTH =
;
private
ByteBuffer r_buff ;
private
ByteBuffer w_buff ;
private
static
String host ;
private
static
int
port;
int
sendBufTotalLen;
int
sendBufLen;
int
sendBufStart;
byte
[] sendBuf;
int
recvBufTotalLen;
int
recvBufLen;
int
recvBufStart;
byte
[] recvBuf;
int
timeout;
String msg;
public
newsSockBase()
{
r_buff = ByteBuffer.allocate(MAX_LENGTH);
w_buff = ByteBuffer.allocate(MAX_LENGTH);
sendBufTotalLen = MAX_LENGTH;
sendBufLen = sendBufStart =
;
sendBuf =
new
byte
[MAX_LENGTH];
recvBufTotalLen = MAX_LENGTH;
recvBufLen = recvBufStart =
;
recvBuf =
new
byte
[MAX_LENGTH];
timeout =
;
}
public
void
setIPandPort(String str,
int
pt)
{
host = str;
port = pt;
}
//这两个函数一定要注意 形参是基类 而实际传入的参数是子类,到时候也是调用子类的参数来做
public
void
getBufFrompara(InewsDetail nD)
{
int
len = nD.encode(sendBuf, sendBufStart, sendBufTotalLen-sendBufStart-sendBufLen);
sendBufLen += len;
}
public
int
decodeBufToPara(InewsDetail nD)
{
int
len = nD.decode(recvBuf, recvBufStart, recvBufLen);
if
(len>
)
//解码正确的时候才做
{
recvBufLen -= len;
recvBufStart += len;
}
return
len;
}
public
void
start(InewsDetail nD)
{
//这里需要先根据传入的参数来
getBufFrompara(nD);
try
{
InetSocketAddress addr =
new
InetSocketAddress(host, port);
// 生成一个socketchannel
sc = SocketChannel.open();
sc.configureBlocking(
false
);
//
// 连接到server
sc.connect(addr);
while
(!sc.finishConnect())
;
System.out.println(
"connection has been established!…"
);
// while (true)
{
// 回射消息 // 复位,清空
w_buff.clear();
w_buff.put(sendBuf,sendBufStart,sendBufLen);
w_buff.flip();
// 转到最开始
// 发送消息
while
(w_buff.hasRemaining())
sc.write(w_buff);
w_buff.clear();
// 进入接收状态
while
(
true
)
{
int
ss=
;
int
count;
r_buff.clear();
while
(ss<timeout*
)
{
count = sc.read(r_buff);
if
(count>
)
break
;
ss++;
Thread.currentThread().sleep(
);
}
if
(ss==timeout)
{
break
;
}
r_buff.flip();
//判断recvBuf能不能放下接收到的数据
if
(r_buff.limit()+recvBufStart+recvBufLen>recvBufTotalLen)
{
//放不下了
//那就先看看前面是不是有空余
if
(recvBufStart>
)
{
for
(
int
i=
;i<recvBufStart;i++)
{
recvBuf
= recvBuf[i+recvBufStart];
}
recvBufStart = ;
}
)
);
nsb.start(nDNS);
System.out.println(]; ];
; ;
}
;
}
;;
)
hour -= ;
System.out.println(seq);
;
}
)
seq = ;
}
] = (+] = (]-)/+] = (]--(StreamID[]-)/+] = (]--(StreamID[]--(StreamID[]-+] = (+] = (]-)+] = (+] = (]-)+] = (+] = (]-)+] = (+] = (]-)+] = (+] = (]-)+] = (+] = (]-)+);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}