This commit is contained in:
Administrator
2022-11-25 21:06:10 +08:00
commit 0b5ff2465b
16 changed files with 956 additions and 0 deletions
@@ -0,0 +1,129 @@
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 List<TCPConnection>tls=new Vector<>();
private KLALBCore klc=new KLALBCore(100);
private InputStream in;
private OutputStream out;
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 {
tls.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();
}
tls.remove(s);
int n=tls.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() {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < tls.size(); i++) {
TCPConnection tll=tls.get(i);
tll.close();
}
klc.close();
}
}