Java套接字:连接重置
我浏览过,搜索过。。。我脑子里什么也没有闪现 我正在服务器和安卓应用程序之间运行聊天类型服务。客户端连接,服务器注册套接字,服务器每10分钟向所有连接的设备发送一条消息 我的问题是,随机出现连接重置异常。我无法追溯问题发生的时间 我的服务器端代码是:Java套接字:连接重置,java,android,sockets,Java,Android,Sockets,我浏览过,搜索过。。。我脑子里什么也没有闪现 我正在服务器和安卓应用程序之间运行聊天类型服务。客户端连接,服务器注册套接字,服务器每10分钟向所有连接的设备发送一条消息 我的问题是,随机出现连接重置异常。我无法追溯问题发生的时间 我的服务器端代码是: final public class ChatRoomService { private final static String AUTHENTICATE = "AUTHENTICATE"; private final static
final public class ChatRoomService {
private final static String AUTHENTICATE = "AUTHENTICATE";
private final static String BROADCAST = "BROADCAST";
private final static String DISCONNECT = "DISCONNECT";
private final static String OK = "OK";
private final static String NOK = "NK";
private final static Logger LOGGER = Logger.getLogger(ChatRoomService.class);
private ServerSocket listener = null;
@Inject
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
@Inject
private PlayerManager playerManager;
PlayerManager getPlayerManager() {
return playerManager;
}
private static HashSet<ChatRoomConnection> connections = new HashSet<ChatRoomConnection>();
public void addConnection(ChatRoomConnection c) {
synchronized(connections) {
connections.add(c);
}
}
public void removeConnection(ChatRoomConnection c) {
synchronized(connections) {
connections.remove(c);
}
}
public void startListeningToChatRoomConnection() throws IOException {
listener = new ServerSocket(9010);
try {
LOGGER.infof("startListening - Start listening on port %s", 9010);
while (true) {
ChatRoomConnection connection = new ChatRoomConnection(listener.accept(), this);
addConnection(connection);
connection.start();
}
} catch (IOException e) {
if (!listener.isClosed())
LOGGER.errorf("listenToChatRoomConnection - Connection lost during connection: %s", e.getMessage());
} finally {
if (listener != null && !listener.isClosed()) {
LOGGER.infof("listenToChatRoomConnection - Stop listening");
listener.close();
}
}
}
public void stopListeningToChatRoomConnection() throws IOException {
if (!listener.isClosed()) {
LOGGER.infof("stopListeningToChatRoomConnection - Stop listening");
listener.close();
listener = null;
// Closing all sockets
for (ChatRoomConnection connection : connections) {
connection.close();
}
// Clear up the connections list
synchronized (connections) {
connections.clear();
}
}
}
public void broadcastToChatRoomClients(Object message) {
synchronized (connections) {
// Log
LOGGER.debugf("Broadcast ChatRoom: %s - %s",
connections.size(),
message.toString());
for (ChatRoomConnection connection : connections) {
LOGGER.debugf("Broadcast ChatRoom to %s", connection.userName);
connection.publish(message);
}
}
}
private ChatRoomService() {
}
private static class ChatRoomConnection extends Thread {
private Socket socket;
private BufferedReader readerFromClient;
private PrintWriter writerToClient;
public String userName;
private ChatRoomService chatCService;
ChatRoomConnection(Socket socket, ChatRoomService chatRoomService) {
super("ChatRoomConnection");
this.socket = socket;
this.chatRoomService = chatRoomService;
}
public void run() {
try {
readerFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writerToClient = new PrintWriter(socket.getOutputStream(), true);
// 1- Authenticate the Device/ Player
writerToClient.println(ChatRoomService.AUTHENTICATE);
writerToClient.flush();
Gson gson = new Gson();
Request request = gson.fromJson(readerFromClient.readLine(), Request.class);
if (chatRoomService.getPlayerManager().isPlayerSignedIn(request.getPlayerId(), request.getSignedInOn())) {
Player player = (Player) chatRoomService.getEntityManager().find(Player.class, request.getPlayerId());
userName = player.getUsername();
LOGGER.infof("listenToChatRoomConnection - Connection established with %s", userName);
writerToClient.println(ChatRoomService.OK);
writerToClient.flush();
while (true)
if ((readerFromClient.readLine() == null) ||
(readerFromClient.readLine().startsWith(ChatRoomService.DISCONNECT)))
break;
} else {
writerToClient.println(ChatRoomService.NOK);
writerToClient.flush();
}
} catch (Exception e) {
LOGGER.errorf("listenToChatRoomConnection - Error with %s: %s", userName, e.getMessage());
e.printStackTrace();
} finally {
try {
if (!socket.isClosed()) {
LOGGER.infof("listenToChatRoomConnection - Connection closed by the client for %s", userName);
socket.close();
}
} catch (IOException e) {
LOGGER.errorf("listenToChatRoomConnection - Can not close socket: %s", e.getMessage());
e.printStackTrace();
} finally {
chatRoomService.removeConnection(this);
}
}
}
public void publish(Object message) {
if (!socket.isClosed()) {
writerToClient.println(ChatRoomService.BROADCAST);
Gson gson = new Gson();
writerToClient.println(gson.toJson(message));
}
}
public void close() {
writerToClient.println(ChatRoomService.DISCONNECT);
try {
LOGGER.infof("listenToChatRoomConnection - Connection closed by the server for %s", userName);
socket.close();
} catch (IOException e) {
LOGGER.errorf("Error when trying to close a socket: %s", e.getMessage());
e.printStackTrace();
}
}
};
}
public class ServerBroadcastManager {
private static final String TAG = ServerBroadcastManager.class.getName();
// Type of messages from the server
static public String AUTHENTICATE = "AUTHENTICATE";
static public String DISCONNECT = "DISCONNECT";
static public String BROADCAST = "BROADCAST";
static public String OK = "OK";
static public String NOK = "NK";
private int networkPort;
private ServerBroadcastListener broadcastListener;
private Socket networkSocket;
BufferedReader in;
PrintWriter out;
public ServerBroadcastManager(Context context, ServerBroadcastListener listener, int port) {
this.networkPort = port;
this.broadcastListener = listener;
}
public void startListening(final Context context) {
Runnable run = new Runnable() {
@Override
public void run() {
// Make connection and initialize streams
try {
networkSocket = new Socket();
networkSocket.connect(new InetSocketAddress(mydomain, networkPort), 30*1000);
in = new BufferedReader(new InputStreamReader(
networkSocket.getInputStream()));
out = new PrintWriter(networkSocket.getOutputStream(), true);
// Process all messages from server, according to the protocol.
while (true) {
String line = in.readLine();
if (line.startsWith(ServerBroadcastManager.AUTHENTICATE)) {
Request request = formatAuthenticateRequest(context);
Gson requestGson = new Gson();
out.println(requestGson.toJson(request));
out.flush();
// Waiting for confirmation back
line = in.readLine();
if (line.startsWith(ServerBroadcastManager.OK)) {
} else if (line.startsWith(ServerBroadcastManager.NOK)) {
}
} else if (line.startsWith(ServerBroadcastManager.BROADCAST)) {
Gson gson = new Gson();
@SuppressWarnings("unchecked")
LinkedHashMap<String,String> broadcast = gson.fromJson(in.readLine(), LinkedHashMap.class);
broadcastListener.processBroadcast(broadcast);
} else if (line.startsWith(ServerBroadcastManager.DISCONNECT)) {
break;
}
}
} catch (UnknownHostException e) {
Log.i(TAG, "Can not resolve hostname");
} catch (SocketTimeoutException e) {
Log.i(TAG, "Connection Timed-out");
broadcastListener.connectionFailed();
} catch (IOException e) {
Log.i(TAG, "Connection raised on exception: " + e.getMessage());
if (!networkSocket.isClosed()) {
broadcastListener.connectionLost();
}
}
}
};
Thread thread = new Thread(run);
thread.start();
}
public void stopListening() {
try {
if (networkSocket != null)
networkSocket.close();
} catch (IOException e) {
Log.i(TAG, "Exception in stopListening: " + e.getMessage());
}
}
private Request formatAuthenticateRequest(Context context) {
Request request = new Request();
SharedPreferences settings = context.getApplicationContext().getSharedPreferences(Constants.USER_DETAILS, 0);
request.setPlayerId(BigInteger.valueOf((settings.getLong(Constants.USER_DETAILS_PLAYERID, 0))));
request.setSignedInOn(settings.getLong(Constants.USER_DETAILS_SIGNEDINON, 0));
return request;
}
}
final公共类聊天室服务{
私有最终静态字符串AUTHENTICATE=“AUTHENTICATE”;
私有最终静态字符串BROADCAST=“BROADCAST”;
专用最终静态字符串DISCONNECT=“DISCONNECT”;
私有最终静态字符串OK=“OK”;
私有最终静态字符串NOK=“NK”;
私有最终静态记录器=Logger.getLogger(ChatRoomService.class);
私有服务器套接字侦听器=null;
@注入
私人实体管理者实体管理者;
公共实体管理器getEntityManager(){
返回实体管理器;
}
@注入
私人玩家管理者玩家管理者;
PlayerManager获取PlayerManager(){
返回playerManager;
}
私有静态HashSet连接=新HashSet();
公共连接(聊天室连接c){
已同步(连接){
添加(c);
}
}
公共无效删除连接(聊天室连接c){
已同步(连接){
连接。移除(c);
}
}
public void startListeningToChatRoomConnection()引发IOException{
侦听器=新服务器套接字(9010);
试一试{
LOGGER.infof(“startListening-在端口%s上开始侦听”,9010);
while(true){
聊天室连接=新的聊天室连接(listener.accept(),this);
添加连接(连接);
connection.start();
}
}捕获(IOE异常){
如果(!listener.isClosed())
errorf(“ListentChatRoomConnection-连接过程中失去连接:%s”,e.getMessage());
}最后{
if(listener!=null&!listener.isClosed()){
infof(“Listent聊天室连接-停止监听”);
listener.close();
}
}
}
public void stopListingToChatroomConnection()引发IOException{
如果(!listener.isClosed()){
LOGGER.infof(“停止侦听到聊天室连接-停止侦听”);
listener.close();
listener=null;
//关闭所有插座
用于(聊天室连接:连接){
connection.close();
}
//清除连接列表
已同步(连接){
连接。清除();
}
}
}
公共无效广播到聊天室客户端(对象消息){
已同步(连接){
//日志
LOGGER.debugf(“广播聊天室:%s-%s”,
connections.size(),
message.toString());
用于(聊天室连接:连接){
LOGGER.debugf(“将聊天室广播到%s”,connection.userName);
连接、发布(消息);
}
}
}
私人聊天室服务(){
}
私有静态类聊天室连接扩展线程{
专用插座;
私有BufferedReader readerFromClient;
私人PrintWriter writerToClient;
公共字符串用户名;
私人聊天室服务聊天室服务;
聊天室连接(套接字、聊天室服务聊天室服务){
超级(“聊天室连接”);
this.socket=socket;
this.chatRoomService=聊天室服务;
}
公开募捐{
试一试{
readerFromClient=new BufferedReader(新的InputStreamReader(socket.getInputStream());
writerToClient=新的PrintWriter(socket.getOutputStream(),true);
//1-验证设备/播放器
writerToClient.println(聊天室服务.AUTHENTICATE);
writerToClient.flush();
Gson Gson=新的Gson();
Request-Request=gson.fromJson(readerFromClient.readLine(),Request.class);
if(聊天室服务.getPlayerManager().isPlayerSignedIn(request.getPlayerId(),request.getSignedOn()){
Player=(Player)聊天室服务.getEntityManager().find(Player.class,request.getPlayerId());
userName=player.getUsername();
LOGGER.infof(“ListentChatRoomConnection-使用%s建立的连接”,用户名);
println(ChatRoomService.OK);
writerToClient.flush();
while(true)
if((readerFromClient.readLine()==null)|
(readerFromClient.readLine().StartWith(ChatRoomService.DISCONNECT)))
打破
}否则{
writerToClient.println(聊天室服务.NOK);
writerToClient.flush();
}
}捕获(例外e){
LOGGER.errorf(“ListentChatRoomConnection-与%s:%s的错误”,用户名,e.getMessage());
e、 printStackTrace();
}最后{
试一试{
如果(!socket.isClosed()){
LOGGER.infof(“ListentChatRoomConnection-客户端为%s关闭的连接”,用户名);
socket.close();
}
}捕获(IOE异常){
errorf(“ListentChatRoomConnection-无法关闭套接字:%s”,e.getMessage());
e、 printStackTrace();
}最后{