开发者

Keeping socket connections in an Array and using them - Java

开发者 https://www.devze.com 2023-04-11 15:13 出处:网络
Is it possible to keep each incoming socket connection in an array and use each whenever we need in Java?

Is it possible to keep each incoming socket connection in an array and use each whenever we need in Java?

I tried the following Array structure but it throws Exception in thread "ServerHandler-0" java.lang.ArrayStoreException: java.net.Socket

My array looks like this:

 Object[][] requests;

And i insert objects into th开发者_如何学JAVAis as follows:

 requests[position][0] = o; //o is a Serializableobject
 requests[position][1] = s; // this is the socket instance

My intention is to use a socket pulled from the array:

Socket s = (Socket) requests[position][1];
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(o);

thanks.


To get rid of the ArrayStoreException I would create a Request-class which holds the information and then store the Request in the array. This way you don't need to do a lot of unnecessary casting and don't need to use Object as the type of the array. I can also recommend you to have a look at java.nio where you use channels and selectors to choose desired sockets, which I think is what you are trying to do.


Have you initialized requests[position] to new Object[2]?

0

精彩评论

暂无评论...
验证码 换一张
取 消