- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我浏览、搜索过……但我的脑海中却没有任何 Spark !
我正在服务器和 Android 应用程序之间运行聊天类型服务。客户端连接,服务器注册套接字,服务器每 10 分钟向所有连接的设备发送一条消息。
我的问题是随机出现连接重置异常。我无法追溯到问题发生的时间。
我的服务器端代码是:
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;
}
}
我最后的手段可能是将我的服务器移动到另一个位置,看看这是否与我的宽带路由器有关。我注意到,尽管端口转发正确,但我的一些 HTTP 调用也未到达服务器。
谢谢。大卫。
最佳答案
我在源代码中找不到服务器每 10 分钟向所有连接的客户端发送一条消息的位置,但我在使用持久的 WebSocket 连接时遇到了连接重置异常。我通过确保每分钟从客户端发送一些数据(乒乓消息)来解决这个问题。
当时,我将问题追溯到我的家庭路由器,它在 5 分钟后简单地关闭了所有空闲连接,但防火墙也可以表现出相同的行为。在传输数据之前,服务器或客户端都不会注意到连接已关闭。如果客户端期待来自服务器的数据,这对于客户端来说尤其令人讨厌 - 该数据永远不会到达。因此,让客户端有责任检查连接是否仍然有效(并在需要时重新连接)。
自从引入客户端每分钟发送一次乒乓消息以来,我还没有看到连接重置异常。
关于Java套接字: Connection reset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21852728/
每次暂存文件时,如果您需要取消暂存文件,Git 都会提供有用的说明: (use "git reset HEAD ..." to unstage) 不过体面Git Tutorials by Atlass
我需要添加几个文件以将它们组合到一个提交中,但我必须排除其中一个。在 this answer ,执行此操作的代码是: git add -u git reset -- file_to_ignore.da
这个问题在这里已经有了答案: What are typical use cases of git-reset's --merge and --keep flags? (4 个答案) 关闭 6 年前。
有时候,进行了错误的提交,但是还没有push到远程分支,想要撤销本次提交,可以使用git reset –-soft/hard命令。 1、二者区别: git reset –-soft:回退到某个版
我认为:软重置:从重置向量启动。硬复位:拉CPU的电平。 最佳答案 硬复位当然意味着整个CPU芯片及其所有外设都被复位。造成这种情况的原因可能有很多:复位引脚被外部拉高、时钟故障、片内低电压检测、看门
$python manage.py reset Unknown command: 'reset' Type 'manage.py help' for usage. 在django 1.6中是否取消了这
我是 git 的新手,所以问题可能很简单,git reset --hard HEAD 和 git reset --hard 有什么区别? 最佳答案 HEAD 在您未指定该参数时是隐含的。 但是,您可以
我使用 apollo-link-state 来本地存储错误,但清除缓存后出现以下错误。 我已在 apollo 客户端配置选项中将 errors 的默认值设置为空数组 []。 但是,在 apolloCl
我正在使用 bool 数组来存储标志(类似于“已更改”)。数组的大小是静态的,在编译时已知。 我需要定期重置数组,即将所有元素设置为 false。我应该使用常规数组和类似 memset 或 memcp
在 git 文档(和许多 SO 线程)中,推荐使用这种重置方法: $ git reset --soft HEAD^ ;# go back to WIP state $ git reset
在我的实验中,我没能发现两者之间的任何功能差异 git reset --hard 和 git reset --merge 使用说明也没有给出任何提示 --hard res
如何重置所有列过滤器?调用 reset() 似乎重置了表,但过滤器的所有字段保持不变。 最佳答案 您可以将输入值绑定(bind)到表的过滤器,如下所示: 注意 [value] 绑定(bind)。 关
使用 std::unique_ptr::reset,您可以轻松地将您的实例恢复到新状态。 C++11 之前,为了实现类似的行为,我看到很多类都定义了一个 Reset() 方法来重置其所有内部成员。但现
为了恢复工作树和索引中的更改,此答案 ( https://stackoverflow.com/a/5812972/8278160) 建议运行以下命令: git reset --hard 运行它是否与运
我目前正在测试竞技场。我本来以为这段代码会编译,但在运行时失败了,令人惊喜的是,编译器发现了这个问题。但我不知道它的推理是否正确。有人能给我解释一下吗?。错误:。来自umpalo的相关代码:
我目前正在测试竞技场。我本来以为这段代码会编译,但在运行时失败了,令人惊喜的是,编译器发现了这个问题。但我不知道它的推理是否正确。有人能给我解释一下吗?。错误:。来自umpalo的相关代码:
我正在尝试在不触发“重置”事件的情况下重置我的收藏。我已经设置了我的收藏来收听“重置”和“添加”事件 @.listenTo(@options.muses, 'add', @addOne) @.list
根据http://en.cppreference.com/w/cpp/memory/unique_ptr/reset , void reset( pointer ptr = pointer() );
我有一个别名,unstage,用于从暂存区域中删除更改。 unstage = reset -- 我注意到 git 的帮助建议改为 git reset HEAD。我还注意到 git rm --cache
这个问题在这里已经有了答案: What's the difference between HEAD^ and HEAD~ in Git? (17 个答案) 关闭 6 年前。 git reset --
我是一名优秀的程序员,十分优秀!