我正在尝试将连接到单个远程服务器的两个套接字客户端互连。案例是:
- Client_1] 连接到服务器
- Client_2] 连接到服务器
- Server] 在 Client_1 和 Client_2 之间创建隧道
- Client_1] 写“某事”
- Client_2](正在等待一些消息)通过 Client_1 接收“某物”
反之亦然。
那是我的代码:
package jtestsock;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
/**
*
* @author massimodeluisa
*/
public class Server extends Thread{
private List<Socket> clients;
private ServerSocket server;
private int port = 5001;
private BufferedReader input;
private PrintWriter output;
public Server() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Impossibile istanziare il server: "+e.getMessage());
}
}
@Override
public void run() {
System.out.println("Waiting for client message...");
//
// The server do a loop here to accept all connection initiated by the
// client application.
//
while (true) {
try {
Socket socket = server.accept();
System.out.println("Connection Received!");
clients.add(socket);
/* read response */
input = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
output = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())));
if(clients.size()>0){
Socket first = new Socket();
Socket second = new Socket();
first = clients.get(1);
second= clients.get(2); // || second = socket;
// ??? Tunneling input and output between two clients
}
} catch (IOException e) {
System.out.println("Client connection error: "+e.getMessage());
}
}
}
}
任何人都可以帮助我吗?谢谢 :)
更新:
我想在两个客户端之间建立点对点连接,传递给我的服务器,就像代理服务器一样......
服务器必须接受两个以上的连接,并且在服务器上创建两个线程用于写入和读取将消息从一个客户端重定向到另一个客户端,CPU 将饱和。
(ps.对不起我的英语XD)