I'v은 ServerSocket의에 객체를 전송하는 멀티 스레드를 사용하는 코드를 가지고 (현재 및 localY을하지만, 로컬 네트워크에서 미래에)자바 소켓 ObjectOutputStream에 멀티 스레드
보내고 목적에 사용 :
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;
}
주요 방법 :
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 스레드 beetwen 데이터를 교환하는 데 사용되는 개체입니다. 스레드에서
실행 방법 :
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) {
}
}
하지만 매우 느리게 작동합니다. 왜냐하면 필요할 때마다 Socket과 ObjectOutputStream을 생성하기 때문입니다. 나는 하나 개의 소켓 하나 OOS를 생성하고 이런 식으로 사용하려고 :
{
Socket s = new Socket("localhost", 9990);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); }
다음
oos.writeUnshared(object);
oos.flush();
oos.writeUnshared(object);
을 내가 OOS 두 번 다시 사용하려고하면하지만 난 소프트웨어는 발생 얻을 연결 중단 : 소켓 쓰기 오류 . 내가 얼마나 쓰레드를 쓰는지는 중요하지 않다.
초당 많은 수의 (예 : 100k) 물체를 보낼 수있는 가능성은 무엇입니까? 서버 측에서
내가 수행
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;
}
"주요 방법"
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();
}
}
왜 스레드를 시작할 때 soc에서 동기화합니까? 여러 스레드의 자원을 사용하는 경우 자원을 동기화해야합니다. 그리고 동기화 된 블록을 짧게 유지하십시오. 또는 심지어없이 지내보십시오. 동기화는 엄청난 성능 저하 요인입니다. – Fildor
현재 동기화 (동기화되지 않은 상태에서 하나의 스레드를 사용하는 경우에도 성능에 문제가 있음)에서 동기화에 문제가 없습니다. – user1055201
확실히 디자인에 더 많은 구조를 가져와야합니다. 죄책감은 없지만 한 곳에서 너무 많은 일을하지 않으려 고 노력하십시오 ... – Fildor