FixFX

Network Issues

Comprehensive guide to understanding and resolving network-related problems in CitizenFX.

Network problems can cause various issues in your CitizenFX server, from player disconnections to poor performance. This guide will help you diagnose and resolve these issues for both server owners and developers.

Common Causes

  1. Connection Problems

    • High latency
    • Packet loss
    • Connection timeouts
    • DNS resolution issues
    • ISP routing problems
    • Client-side network issues
  2. Bandwidth Issues

    • Insufficient bandwidth
    • Network congestion
    • Rate limiting
    • Large data transfers
    • Resource streaming issues
    • Client download problems
  3. Firewall/NAT Issues

    • Port blocking
    • NAT traversal problems
    • Firewall rules
    • Security software interference
    • Router configuration
    • VPN interference

Server Owner Solutions

1. Network Configuration

# Add to your server.cfg
setr sv_netRateLimit 1000000  # Network rate limit in bytes
setr sv_netRateLimitPerClient 100000  # Per-client rate limit
setr sv_maxClients 32  # Maximum number of clients
setr sv_maxPlayers 32  # Maximum number of players
setr sv_netRateLimitBurst 2000000  # Burst rate limit
setr sv_netRateLimitPerClientBurst 200000  # Per-client burst limit
setr sv_netRateLimitPerClientInterval 1000  # Per-client interval
setr sv_netRateLimitPerClientTimeout 5000  # Per-client timeout

2. Port Forwarding and Firewall

# Required ports for FiveM
TCP: 30120  # Main server port
UDP: 30120  # Main server port
TCP: 30110  # Optional: txAdmin port
TCP: 40120  # Optional: txAdmin port
 
# Firewall rules
allow tcp/udp 30120  # Main server port
allow tcp 30110      # Optional: txAdmin port
allow tcp 40120      # Optional: txAdmin port

3. Network Monitoring

# Network diagnostic commands
ping server_ip  # Check latency
traceroute server_ip  # Check routing
netstat -an | grep 30120  # Check port usage
resmon  # Monitor resource performance
netgraph  # Monitor network performance
net_statsFile "network_metrics.csv"  # Log network metrics

4. Server Optimization

# Add to your server.cfg
setr sv_enforceGameBuild 2699  # Enforce specific game build
setr sv_minClientVersion 1.0.0  # Minimum client version
setr sv_scriptHookAllowed 0  # Disable script hook access
setr sv_pureLevel 2  # Enable strict file integrity checks
setr sv_filterRequestControl 1  # Enable request filtering
setr sv_requestParanoia 1  # Enable stricter request validation

5. Resource Management

# Add to your server.cfg
setr sv_maxResourceMemory 512  # MB of memory per resource
setr sv_maxResourceThreads 8  # Maximum concurrent resource threads
setr sv_threadPoolSize 4  # Number of worker threads
setr sv_resourcePriority "high"  # Set resource priority
setr sv_resourceStartupTimeout 30000  # 30 second timeout

Developer Solutions

1. Connection Handling

-- Example of robust connection handling
local function handlePlayerConnection(source)
    local success, error = pcall(function()
        -- Validate connection
        if not source then return false end
        
        -- Check player state
        local playerState = GetPlayerState(source)
        if not playerState then return false end
        
        -- Initialize player data
        local success = InitializePlayerData(source)
        if not success then
            print('Failed to initialize player data')
            return false
        end
        
        return true
    end)
    
    if not success then
        print('Connection handling failed:', error)
        return false
    end
    return true
end
 
-- Example of connection monitoring
local function monitorConnection(source)
    local lastPing = GetPlayerPing(source)
    if lastPing > 200 then  -- 200ms threshold
        print('Warning: High ping for player', source, ':', lastPing, 'ms')
    end
end

2. Network Optimization

-- Example of network optimization
local function sendOptimizedData(source, data)
    -- Compress data if large
    if #data > 1000 then
        data = CompressData(data)
    end
    
    -- Split into chunks if necessary
    local chunks = SplitIntoChunks(data, 1000)
    
    -- Send chunks with delay
    for i, chunk in ipairs(chunks) do
        TriggerClientEvent('receiveData', source, chunk, i, #chunks)
        Wait(10)  -- Small delay between chunks
    end
end
 
-- Example of rate-limited updates
local lastUpdate = {}
local function rateLimitedUpdate(source, data)
    local currentTime = GetGameTimer()
    if not lastUpdate[source] or currentTime - lastUpdate[source] > 100 then
        lastUpdate[source] = currentTime
        TriggerClientEvent('updateData', source, data)
    end
end

3. Error Recovery and Validation

-- Example of error recovery
local function handleNetworkError(source, error)
    print('Network error for player', source, ':', error)
    
    -- Attempt recovery
    local success = ReconnectPlayer(source)
    if not success then
        -- If recovery fails, handle gracefully
        print('Failed to recover player connection')
        DropPlayer(source, 'Network error. Please reconnect.')
    end
end
 
-- Example of data validation
local function validateNetworkData(data)
    if type(data) ~= 'table' then
        return false, 'Invalid data type'
    end
    
    -- Validate required fields
    if not data.requiredField then
        return false, 'Missing required field'
    end
    
    -- Validate data size
    local json = json.encode(data)
    if #json > 16000 then
        return false, 'Data too large'
    end
    
    return true
end

4. Performance Monitoring

-- Add performance monitoring to network operations
local function monitoredNetworkOperation(source, data)
    local startTime = GetGameTimer()
    
    -- Your network operation code here
    
    local endTime = GetGameTimer()
    local duration = endTime - startTime
    
    if duration > 10 then  -- 10ms threshold
        print('Warning: Network operation took', duration, 'ms')
    end
end
 
-- Example of bandwidth monitoring
local bandwidthUsage = {}
local function monitorBandwidth(source, dataSize)
    bandwidthUsage[source] = (bandwidthUsage[source] or 0) + dataSize
    if bandwidthUsage[source] > 1000000 then  -- 1MB threshold
        print('Warning: High bandwidth usage for player', source)
    end
end

Best Practices

For Server Owners

  1. Regular Monitoring

    • Monitor network performance
    • Check for connection issues
    • Review error logs
    • Monitor bandwidth usage
    • Check player ping and latency
  2. Configuration Management

    • Keep network settings appropriate
    • Enable security features
    • Configure proper rate limits
    • Maintain firewall rules
    • Update server configuration
  3. Resource Management

    • Monitor resource performance
    • Check for network-heavy resources
    • Review resource loading order
    • Maintain resource updates
    • Test resource compatibility

For Developers

  1. Code Optimization

    • Minimize network traffic
    • Use efficient data structures
    • Implement proper caching
    • Use appropriate compression
    • Monitor bandwidth usage
  2. Error Prevention

    • Validate network data
    • Handle disconnections
    • Implement timeouts
    • Use proper cleanup
    • Monitor performance
  3. Security Implementation

    • Validate input data
    • Implement proper authentication
    • Use secure connections
    • Monitor for abuse
    • Handle edge cases

Additional Resources

Always monitor your network performance and implement proper error handling to prevent connection issues. Regular monitoring and maintenance are essential for optimal server performance.

For more information about network management, refer to the relevant sections in the documentation and server commands reference.