我有一个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;
}
}
答案 0 :(得分:1)
如果您尝试将数据从一个套接字转发到另一个套接字,那么最好直接使用套接字流而不是装饰它们。
正如其他海报所建议你应该使用线程来做到这一点。它会让生活更轻松。然后,您可以使用线程执行基本的输出流复制,如下所示。
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
流。你的线程或runnable的run方法看起来像这样。
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 */
}
}
}
}
答案 1 :(得分:1)
您无法在一个帖子中正确执行此操作。你需要两个线程,每个方向一个。每个线程只读取和写入,直到遇到EOS。并且不要使用available():只是在读取中阻塞。设置读取超时以避免病态情况。