You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Netty框架多端口监听问题:摄像头流媒体定向转发需求求助

Fixing Port-Specific Forwarding for Multi-Camera Webcam Streaming

Got it, let's work through solving your multi-camera streaming issue. The core problem here is that your current server doesn't track which incoming stream belongs to which port, so it can't route data to the correct client2. Here's a step-by-step solution tailored to your needs:

1. Build a Port-to-Client Mapping on the Server

First, you need the server to keep track of which clients are sending streams on specific ports, and which clients want to receive those streams. Use a pair of maps to manage this:

// Server-side: Map port numbers to their respective sender/receiver connections
private static final Map<Integer, Socket> portToSender = new HashMap<>();
private static final Map<Integer, List<Socket>> portToReceivers = new HashMap<>();

When a client connects, have it send an initial message identifying itself as a sender or receiver along with the target port. For example:

// On server connection handling
BufferedReader clientReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String clientIdentity = clientReader.readLine(); // Format: "sender:5001" or "receiver:5001"
String[] identityParts = clientIdentity.split(":");
int targetPort = Integer.parseInt(identityParts[1]);

if ("sender".equals(identityParts[0])) {
    portToSender.put(targetPort, clientSocket);
} else if ("receiver".equals(identityParts[0])) {
    portToReceivers.computeIfAbsent(targetPort, k -> new ArrayList<>()).add(clientSocket);
}

2. Configure Client1 to Bind to a Specific Port

Modify your client1 code to bind to the desired local port before connecting to the server, then notify the server of its role and port:

// Client1 (sender) code
int localStreamPort = 5001; // Specify your desired port here
Socket senderSocket = new Socket();
senderSocket.bind(new InetSocketAddress("localhost", localStreamPort)); // Bind to local port
senderSocket.connect(new InetSocketAddress("SERVER_IP", SERVER_PORT));

// Notify server this is a sender for port 5001
PrintWriter serverWriter = new PrintWriter(senderSocket.getOutputStream(), true);
serverWriter.println("sender:" + localStreamPort);

// Now start sending webcam frames as before...

3. Implement Port-Directed Data Forwarding

Update the server's data forwarding logic to only send frames from a sender to receivers registered for the same port:

// Server-side: Handle incoming data from a sender
Socket senderSocket = // Your existing sender socket reference
int targetPort = getPortForSender(senderSocket); // Look up the port tied to this sender

InputStream frameInputStream = senderSocket.getInputStream();
byte[] frameBuffer = new byte[4096];
int bytesRead;

while ((bytesRead = frameInputStream.read(frameBuffer)) != -1) {
    // Get all receivers subscribed to this port
    List<Socket> receivers = portToReceivers.getOrDefault(targetPort, Collections.emptyList());
    // Forward the frame to each receiver
    for (Socket receiver : receivers) {
        try {
            OutputStream receiverOutput = receiver.getOutputStream();
            receiverOutput.write(frameBuffer, 0, bytesRead);
            receiverOutput.flush();
        } catch (IOException e) {
            // Remove disconnected receivers from the map
            receivers.remove(receiver);
        }
    }
}

// Helper method to reverse-lookup port from sender socket
private static int getPortForSender(Socket senderSocket) {
    for (Map.Entry<Integer, Socket> entry : portToSender.entrySet()) {
        if (entry.getValue().equals(senderSocket)) {
            return entry.getKey();
        }
    }
    return -1;
}

4. Fix the Dual-Camera Conflict

With this port mapping in place, each camera's stream is isolated to its own port. When you set up the second camera:

  • Have its client1 bind to a different port (e.g., 5002)
  • Have the corresponding client2 subscribe to port 5002 by sending "receiver:5002" to the server
    The server will now route each stream only to the clients that requested it, eliminating the cross-stream interference you saw before.

5. Add Robustness Checks

To make the system more reliable:

  • Clean up dead connections: Periodically check if sockets are closed and remove them from the maps
  • Handle port conflicts: Add error handling for when client1 can't bind to the desired port (e.g., prompt the user to pick another)
  • Log activity: Add simple logging to track which ports are active, how many receivers are connected, and any errors

内容的提问来源于stack exchange,提问作者Gorgeo

火山引擎 最新活动