141 lines
2.7 KiB
Java
141 lines
2.7 KiB
Java
package org.kne.cloud.network.klalb;
|
|
|
|
import java.io.BufferedInputStream;
|
|
import java.io.BufferedOutputStream;
|
|
import java.io.DataInputStream;
|
|
import java.io.DataOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.io.OutputStream;
|
|
import java.net.Socket;
|
|
import java.util.*;
|
|
public class KLALBServerProtocol {
|
|
private KLALBCore klc=new KLALBCore(100);
|
|
private List<TCPConnection>tcps=new Vector<>();
|
|
|
|
|
|
private InputStream in;
|
|
private OutputStream out;
|
|
|
|
|
|
private volatile boolean closed=true;
|
|
public void startLocal() {
|
|
|
|
Thread upo=ThreadTool.makeVThreadIfSupport("本地接收线程",()->{
|
|
try{
|
|
|
|
while(true) {
|
|
byte[]b=new byte[Consts.BLOCKSIZE];
|
|
int size=in.read(b);
|
|
if(size==-1)
|
|
break;
|
|
klc.packDataBlock(b,size);
|
|
}
|
|
}catch(InterruptedException s) {
|
|
|
|
}catch(Exception e) {
|
|
e.printStackTrace();
|
|
}finally {
|
|
closeALL();
|
|
}
|
|
});
|
|
Thread downo=ThreadTool.makeVThreadIfSupport("本地发送线程",()->{
|
|
try{
|
|
while(true) {
|
|
|
|
out.write(klc.unpackDataBlock());
|
|
out.flush();
|
|
}
|
|
}catch(InterruptedException s) {
|
|
|
|
}catch(Exception e) {
|
|
e.printStackTrace();
|
|
}finally {
|
|
closeALL();
|
|
}
|
|
});
|
|
upo.start();
|
|
downo.start();
|
|
}
|
|
public void handleSocket(TCPConnection s) throws IOException {
|
|
tcps.add(s);
|
|
Thread up=ThreadTool.makeVThreadIfSupport("远程发送线程",()->{
|
|
try{
|
|
while(true) {
|
|
klc.sendDataBlock(s);
|
|
}
|
|
}catch(InterruptedException s1) {
|
|
|
|
}catch(Exception e) {
|
|
}
|
|
});
|
|
Thread down=ThreadTool.makeVThreadIfSupport("远程接收线程",()->{
|
|
try{
|
|
while(true) {
|
|
klc.receiveDataBlock(s);
|
|
}
|
|
}catch(InterruptedException s1) {
|
|
|
|
}catch(Exception e) {
|
|
up.interrupt();
|
|
}
|
|
});
|
|
|
|
up.start();
|
|
down.start();
|
|
try {
|
|
up.join();
|
|
down.join();
|
|
} catch (InterruptedException e) {
|
|
e.printStackTrace();
|
|
}
|
|
tcps.remove(s);
|
|
int n=tcps.size();
|
|
if(n<=0) {
|
|
closeALL();
|
|
System.out.println("连接已关闭");
|
|
}
|
|
}
|
|
public InputStream getIn() {
|
|
return in;
|
|
}
|
|
|
|
public void setIn(InputStream in) {
|
|
this.in = in;
|
|
}
|
|
|
|
public OutputStream getOut() {
|
|
return out;
|
|
}
|
|
|
|
public void setOut(OutputStream out) {
|
|
this.out = out;
|
|
}
|
|
public void closeALL() {
|
|
closed=false;
|
|
try {
|
|
in.close();
|
|
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
try {
|
|
out.close();
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
for (int i = 0; i < tcps.size(); i++) {
|
|
TCPConnection tll=tcps.get(i);
|
|
tll.close();
|
|
}
|
|
klc.close();
|
|
}
|
|
public List<TCPConnection> getTcps() {
|
|
return tcps;
|
|
}
|
|
public boolean isClosed() {
|
|
return closed;
|
|
}
|
|
|
|
}
|