I'v got code which use multi-thread to send object to ServerSocket (currently localy, but in future in local net)
Used for sending object:
public class SocketToAdapter {
public static void writeObject(Object object) {
try {
give().writeUnshared(object);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
static ObjectOutputStream give() {
Socket s = null;
try {
s = new Socket("localhost", 9990);
s.setTcpNoDelay(true);
return new ObjectOutputStream(s.getOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
main method:
SocketToAdapter soc = new SocketToAdapter();
thread1.setSocket(soc);
thread2.setSocket(soc);
thread3.setSocket(soc);
thread4.setSocket(soc);
thread5.setSocket(soc);
synchronized (valueExchanging) {
synchronized (soc) {
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
valueExchanging is a Object that is used to exchange data beetwen threads.
Run method from thread:
public void run() {
try {
while (true) {
curr = new Object(pair, RandomUtil.getRandomExchange(),
RandomUtil.getRandomTurn());
//not important Business Logic.
int v1 = valueExchanger.getExchangeInTread()+1;
int v2 = valueExchanger.getExchangeInTread()-100;
curr = new Object(pair, BigInteger.valueOf(v1),
BigInteger.valueOf(v2));
//
SocketToAdapter.writeObject(curr);
valueExchanger.setExchangeInTread(v1);
Thread.sleep(0, 1);
}
} catch (InterruptedException iex) {
}
}
That works but very slowly. Propably because I create Socket and ObjectOutputStream every time when is need. I try to create one Socket and one OOS and use it like this:
{
Socket s = new Socket("localhost", 9990);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); }
and then
oos.writeUnshared(object);
oos.flush();
oos.writeUnshared(object);
but if I try to reuse oos second time i get Software caused connection abort: socket write error. Doesnt matter how much thread i use.
What im need is possiblity to send many (e.g. 100k) object per second, any sugesstions?
on server side i do:
Serwer.java:
ServerSocket ss;
public static void pre()throws IOException, ClassNotFoundException {
ss = new ServerSocket(9990);
}
public static Object start() throws IOException, ClassNotFoundException {
Object o = null;
Socket s = ss.accept();
while (!s.isClosed()) {
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
o = (Object) ois.readObject();
ois.close();
s.close();
}
ss.close();
return o;
}
"main method"
while (true) {
try {
Serwer.pre();
Object o = Serwer.start();
//im do somethink with that object o.
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}