gpt4 book ai didi

java - 套接字镜像发送但不接收

转载 作者:行者123 更新时间:2023-11-30 09:42:33 26 4
gpt4 key购买 nike

我有一个 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;
}
}

最佳答案

如果您尝试将数据从一个套接字转发到另一个套接字,那么直接使用套接字流而不是修饰它们可能是更好的主意。

正如其他发帖人所建议的那样,您应该使用线程来执行此操作。这将使生活更轻松。然后,您可以使用线程执行基本的输入输出流复制,如下所示。

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

关于java - 套接字镜像发送但不接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8618953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com