diff --git a/background.js b/background.js index 82fff8b..6c8136a 100644 --- a/background.js +++ b/background.js @@ -379,8 +379,34 @@ function setupConnectionHandlers() { console.error('[Proxy] Accept error:', errorInfo); }); - // Handle incoming data from clients + // Handle receive errors + chrome.sockets.tcp.onReceiveError.addListener(function(info) { + var socketId = info.socketId; + var resultCode = info.resultCode; + console.error('[Proxy] Receive error on socket ' + socketId + ': ' + resultCode); + + // Clean up connections + if (connections[socketId]) { + closeConnection(socketId); + } else if (reverseConnections[socketId]) { + closeConnection(reverseConnections[socketId]); + } + }); + + // Handle disconnects (EOF detection - zero byte receive) chrome.sockets.tcp.onReceive.addListener(function(receiveInfo) { + if (receiveInfo.data.byteLength === 0) { + var socketId = receiveInfo.socketId; + console.log('[Proxy] Socket ' + socketId + ' disconnected (EOF)'); + if (connections[socketId]) { + closeConnection(socketId); + } else if (reverseConnections[socketId]) { + closeConnection(reverseConnections[socketId]); + } + return; + } + + // If not EOF, let the main onReceive handler handle the data var socketId = receiveInfo.socketId; // Check if this is data from a client or destination @@ -395,31 +421,6 @@ function setupConnectionHandlers() { console.warn('[Proxy] Received data from unknown socket: ' + socketId); } }); - - // Handle receive errors - chrome.sockets.tcp.onReceiveError.addListener(function(errorInfo) { - console.error('[Proxy] Receive error on socket ' + errorInfo.socketId + ':', errorInfo.resultCode); - - // Clean up connections - if (connections[errorInfo.socketId]) { - closeConnection(errorInfo.socketId); - } else if (reverseConnections[errorInfo.socketId]) { - var clientSocketId = reverseConnections[errorInfo.socketId]; - closeConnection(clientSocketId); - } - }); - - // Handle disconnects - chrome.sockets.tcp.onReceive.addListener(function(receiveInfo) { - if (receiveInfo.data.byteLength === 0) { - console.log('[Proxy] Socket ' + receiveInfo.socketId + ' disconnected (EOF)'); - if (connections[receiveInfo.socketId]) { - closeConnection(receiveInfo.socketId); - } else if (reverseConnections[receiveInfo.socketId]) { - closeConnection(reverseConnections[receiveInfo.socketId]); - } - } - }); } function initializeProxy() {