Если вы пытаетесь переслать данные из одного сокета в другой, вероятно, было бы лучше использовать потоки сокетов напрямую, а не украшать их.
Как и другие авторы предложили вам использовать темы для этого. Это облегчит жизнь. Затем вы можете использовать потоки, чтобы выполнить базовое копирование в потоковом режиме, как показано ниже.
public static void streamCopy(InputStream in, OutputStream out)
throws IOException{
byte[] data = new byte[1024];
int length;
do{
length = in.read(data);
if(length > 0){
out.write(data, 0, length);
out.flush();
}
}while(length != -1);
}
Когда вышеприведенный метод вернется, вы прочитаете весь поток in
и запишите его в поток out
. Ваш метод run для вашего потока или runnable может выглядеть примерно так:
public void run() {
Socket inSock = null;
Socket outSock = null;
try{
inSock = new Socket(inHost, inPort);
outSock = new Socket(inHost, inPort);
/* Set up some socket options here (timeouts, buffers etc)*/
/* Insert pre copy actions */
/* This method won't return until inSock's inputStream hits end of stream.
* and all the data has been written to outSock's outputStream and flushed. */
streamCopy(inSock.getInputStream(), outSock.getOutputStream());
/* In order to really do this correctly you should create an
* application protocol that verifies the upstream receiver
* is actually getting the data before you close the socket. */
/* Insert post copy actions */
}catch(Exception e){
/* Corrective action or logging here */
}finally{
/* Don't forget to close the sockets. */
if(inSock != null){
try{
inSock.close();
}catch(Exception e){
/* Don't care */
}
}
if(outSock != null){
try{
outSock.close();
}catch(Exception e){
/* Don't care */
}
}
}
}