【发布时间】:2016-06-03 06:59:35
【问题描述】:
我有一个套接字客户端应用程序,它在指定端口上的主线程中侦听传入连接,接受传入连接并为每个连接启动一个用户线程。
此设置可以运行几天,然后应用程序停止接受任何新的新连接。恢复的唯一方法是重新启动应用程序。我不知道为什么会发生这种情况...... 这是我的主线程,它为每个连接接受并启动一个新线程。
while(ServerOn)
{
ServerSocket myServerSocket;
private static ArrayList<Socket> connecitons;
try {
// Accept incoming connections.
Socket conn = myServerSocket.accept();
// adds the new connections to the socket
connections.add(conn);
// accept() will block until a client connects to the server.
// If execution reaches this point, then it means that a client
// socket has been accepted.
// For each client, we will start a service thread to
// service the client requests.
// Start a Service thread
ServerThread cliThread = new ServerThread(conn);
cliThread.start();
} catch (IOException ioe) {
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
try {
myServerSocket.close();
System.out.println("Server Stopped");
} catch (Exception ioe) {
System.out.println("Problem stopping server socket");
System.exit(-1);
}
}
请帮忙。
编辑 1
这是类声明:
class ServerThread extends Thread {
Socket conn;
boolean m_bRunThread = true;
InputStream in = null;
OutputStream outStream = null;
//calling the 1-argument constructor with the socket parameters
ServerThread(Socket s) {
conn = s;
}
//Subclasses of Thread should override this method.
public void run() {
//lot of variables declared here.
try {
// Class InputStream is used for receiving data (as bytes) from client.
in = conn.getInputStream();
// Class OutputStream is used for sending data (as bytes) to client.
outStream = conn.getOutputStream();
/*
* 1. Go to Read Thread
* 2. Check for incoming data stream from Client
* 3. Go to read routine and process only if the data is received from the client
* 4. If there is no data for X minutes then close the socket.
*/
conn.setSoTimeout(time in milliseconds);
String inLine=null;
while (m_bRunThread) {
// read incoming stream
while ((c=in.read(rec_data_in_byte))!= -1)
{...............
然后run方法继续……
【问题讨论】:
-
编辑了代码。它的 while 循环设置为 true。
-
您确定您的应用程序的输出到 stdout/stderr 对您是可见的吗?你看,仅仅在某处打印异常并不是一种非常可靠的处理方式。
-
@Jägermeister- 是的,我知道,但这是主线程,如果它退出,整个应用程序应该停止,这不会发生。创建的客户端线程继续无缝工作,只是不再接受新的传入连接。
-
@Jayesh Tripathi。即使主线程停止,如果有其他线程(不是守护进程)正在运行,应用程序也不会停止。顺便说一句,最后一行中的 System.exit 并不总是被调用。
-
除非客户端线程将自己从数组中删除,否则即使拥有它也没有多大意义,如果你拥有它,你必须同步所有对它的访问。例如,您可能会收到
ConcurrentModificationException,这是一个运行时异常。当您的应用程序停止接受时,(a) 它是否仍在运行,并且 (b)netstat -nap tcp是否仍将端口显示为 LISTENING?我也想知道ServerThread的构造函数到底做了什么。如果它做任何 I/O,甚至构造对象流,它也不应该。
标签: java multithreading sockets