插座镜发送,但没有收到

我有反映从客户机服务器的远程服务器的连接的Java程序。 镜发送数据发现,但不接收。 我不能为我的生命找出原因。 这里是我的代码:

Socket client = new Socket("127.0.0.1", 42001); System.out.println("Connected to client!"); Socket server = new Socket(serverAddress, serverPort); System.out.println("Connected to server!"); BufferedReader clientin = new BufferedReader(new InputStreamReader(client.getInputStream())); BufferedWriter scratchout = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); BufferedReader serverin = new BufferedReader(new InputStreamReader(server.getInputStream())); BufferedWriter serverout = new BufferedWriter(new OutputStreamWriter(server.getOutputStream())); int i; boolean serverNeedsFlush = false; boolean clientNeedsFlush = false; while (true) { while (clientin.ready()) { i = clientin.read(); serverout.write(i); serverNeedsFlush = true; } if(serverNeedsFlush) { serverout.flush(); serverNeedsFlush = false; } while (serverin.ready()) { i = serverin.read(); System.out.print((char)i); scratchout.write(i); clientNeedsFlush = true; } if(clientNeedsFlush) { scratchout.flush(); clientNeedsFlush = false; } }

--------------解决方案-------------

如果你试图从一个插座转发到另一个数据它很可能是一个更好的主意使用socket流,而不是直接装饰他们。

正如其他海报建议你应该使用线程来做到这一点。 它将使生活更轻松。 然后,您可以用线程做一个基本以出流复制像下面。

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流。 你运行你的线程或可运行的方法可以是这个样子。

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 */
}
}
}
}

你不能在一个线程中执行此操作正常。 你需要两个线程,每个方向一个。 每个线程只是读取和写入,直到遇到EOS。 不要使用可用():只是在读取块。 设置读取超时,以避免病理情况。

分类:java的 时间:2015-03-15 人气:0
本文关键词: java的,插座
分享到:

相关文章

Copyright (C) 55228885.com, All Rights Reserved.

55228885 版权所有 京ICP备15002868号

processed in 0.626 (s). 10 q(s)