Click this for Image result attached 我正在设置服务器(Java),客户端将是webApp(WebSocket)。当客户端断开与服务器的连接时,它将发送无法编码的数据。
PTR
//这是客户端代码
public final class MyServer implements Runnable{
public void run(){
InputStream inputStream = null;;
OutputStream outputStream = null;
BufferedReader bufferedReader = null;
try{
server = new ServerSocket(tcpPort);
while(isRunning){
clientSocket = server.accept(); //waits until a client connects
inputStream = clientSocket.getInputStream();
outputStream = clientSocket.getOutputStream();
doHandShakeToInitializeWebSocketConnection(inputStream, outputStream);
printInputStream(inputStream);
}//while end
}catch(final Exception e){
logger.log(LogLevel.SEVERE, "TCP server error", e);
System.out.println(" catch exception in server>>>");
e.printStackTrace();
unsetIsRunning();
}finally{
if(null != outputStream){
try {
System.out.println(">>> closing outputStream");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != inputStream){
try {
System.out.println(">>> closing inputStream");
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != clientSocket){
try {
System.out.println(">>> closing clientSocket");
clientSocket.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//this is how message from client is decoded
private void printInputStream(InputStream inputStream) throws IOException {
int len = 0;
byte[] b = new byte[1024];
//rawIn is a Socket.getInputStream();
int x=0;
while(isRunning){
System.out.println("inside while x is " + x++);
len = inputStream.read(b);
if(len!=-1){
byte rLength = 0;
int rMaskIndex = 2;
int rDataStart = 0;
//b[0] is always text in my case so no need to check;
byte data = b[1];
byte op = (byte) 127;
rLength = (byte) (data & op);
if(rLength==(byte)126) rMaskIndex=4;
if(rLength==(byte)127) rMaskIndex=10;
byte[] masks = new byte[4];
int j=0;
int i=0;
for(i=rMaskIndex;i<(rMaskIndex+4);i++){
masks[j] = b[i];
j++;
}
rDataStart = rMaskIndex + 4;
int messLen = len - rDataStart;
byte[] message = new byte[messLen];
for(i=rDataStart, j=0; i<len; i++, j++){
message[j] = (byte) (b[i] ^ masks[j % 4]);
}
b = new byte[1024];
System.out.println("[][][] Printing from inputStream : " + new String(message));
listener.eventReceived(new String(message));
}
}
}
}
下面是我单击客户端断开连接按钮后的结果。请注意所附结果emage中的“第一个”字符。我不确定解码代码是否错误。
[] [] []从inputStream打印:è工作完成