I have to write a class which is accept the socket connection and pass it to Handler class using Spring
My Listener Class is
public class Listener {
static Logger log = Logger.getLogger(Listener.class.getName());
public static void main(String args[]) throws IOException {
int port = 0;
if (args.length < 1) {
System.out.println("Usage: java -jar hovel.jar listenPortNumber");
System.exit(1);
} else {
port = Integer.parseInt(args[0]);
}
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("TCPHandler");
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Listening on TCP port " + port);
for (;;) {
Socket sock = serverSocket.accept();
taskExecutor.execute(new TCPHandler(sock));
}
}
}
My Handler class is
public class TCPHandler implements Runnable {
private Socket moduleSocket;
public TCPHandler(Socket sock) {
moduleSocket = sock;
}
public void run() {
}
}
My Bean.xml is
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="TCPHandler" class="org.hovel.server.TCPHandler">
<constructor-arg type="java.net.Socket">
<null />
</constructor-arg>
</bean>
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>
</beans>
when i pass port number then i got this error
**
Exception in thread "main" java.lang.ClassCastException: org.hovel.server.TCPHandler cannot be cast to org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor at org.hovel.server.Listener.main(Listener.java:27)*
**
Please Help Me
You're requesting the TCPHandler
bean here:
context.getBean("TCPHandler")
That isn't a ThreadPoolTaskExecutor
, so I don't know why you expect it to be. If you want to retrieve the executor, you should be fetching that bean instead, which has an ID of taskExecutor
.
Note that currently you're not actually using your TCPHandler
bean in any useful way, as you're constructing a TCPHandler
explicitly in your main
method.
See more on this question at Stackoverflow