我的桌面应用程序客户端正在通过webSockets
. 我javaWebSocket
在客户端使用 api,并且使用 Apache tomcat 7 的webSocketServlet
. 我不知道我做错了什么,但客户端与网络服务器完美连接并发送聊天消息,但在闲置一段时间后,服务器会自动断开客户端。我希望客户端连接,直到客户端故意不想断开连接。Socket
这是我的 web servlet 和客户端的示例代码。首先是客户端代码
Draft[] drafts = { new Draft_10(), new Draft_17(), new Draft_76(), new Draft_75() };
cc = new WebSocketClient( new URI( uriField.getText() ), (Draft) draft.getSelectedItem() ) {
@Override
public void onMessage( String message ) {
ta.append( "got: " + message + "\n" );
ta.setCaretPosition( ta.getDocument().getLength() );
}
@Override
public void onOpen( ServerHandshake handshake ) {
ta.append( "You are connected to ChatServer: " + getURI() + "\n" );
ta.setCaretPosition( ta.getDocument().getLength() );
}
@Override
public void onClose( int code, String reason, boolean wasClean ) {
ta.append( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n" );
System.out.println("the reason for disconnection is ........ "+wasClean);
ta.setCaretPosition( ta.getDocument().getLength() );
connect.setEnabled( true );
uriField.setEditable( true );
draft.setEditable( true );
close.setEnabled( false );
}
@Override
public void onError( Exception ex ) {
ta.append( "Exception occured ...\n" + ex + "\n" );
ta.setCaretPosition( ta.getDocument().getLength() );
ex.printStackTrace();
connect.setEnabled( true );
uriField.setEditable( true );
draft.setEditable( true );
close.setEnabled( false );
}
};
close.setEnabled( true );
connect.setEnabled( false );
uriField.setEditable( false );
draft.setEditable( false );
cc.connect();
} catch ( URISyntaxException ex ) {
ta.append( uriField.getText() + " is not a valid WebSocket URI\n" );
}
} else if( e.getSource() == close ) {
cc.close();
}
现在这是 servlet 代码。
private static ArrayList<MyStreamBound> mmiList = new ArrayList<MyStreamBound>();
@Override
protected StreamInbound createWebSocketInbound(String protocol) {
return new MyStreamBound();
}
private class MyStreamBound extends StreamInbound{
WsOutbound myoutbound;
@Override
public void onOpen(WsOutbound outbound){
try {
System.out.println("Open Client.");
this.myoutbound = outbound;
mmiList.add(this);
outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onBinaryData(InputStream arg0) throws IOException {
// TODO Auto-generated method stub
}
@Override
protected void onTextData(Reader recievedData) throws IOException {
BufferedReader in = new BufferedReader(recievedData);
String line = null;
StringBuilder rslt = new StringBuilder();
while ((line = in.readLine()) != null) {
rslt.append(line);
}
System.out.println(rslt.toString());
for(MyStreamBound mmib: mmiList){
CharBuffer buffer = CharBuffer.wrap(rslt.toString());
mmib.myoutbound.writeTextMessage(buffer);
mmib.myoutbound.flush();
}
}
@Override
protected void onClose(int status){
System.out.println("Close Client."+status);
mmiList.remove(this);
}