### Use wait_ready Source: https://linksocks.github.io/python/server Example of initializing a server with a forward token. ```python server = Server() server.add_forward_token("ready_token") ``` -------------------------------- ### Initialize Provider and Connector Source: https://linksocks.github.io/guide/quick-start Basic commands to start the provider and connector services. ```bash linksocks provider -t any_token -c your_token -u wss://your-worker.your-subdomain.workers.dev ``` ```bash linksocks connector -t your_token -u wss://your-worker.your-subdomain.workers.dev -p 9870 ``` -------------------------------- ### Enable HTTP API Source: https://linksocks.github.io/guide/quick-start Start the server with an API key for dynamic management. ```bash linksocks server --api-key your_api_key ``` -------------------------------- ### Initialize Server for Token Management Source: https://linksocks.github.io/python/server Basic setup for token management operations. ```python server = Server() ``` -------------------------------- ### Install LinkSocks via Go Source: https://linksocks.github.io/ Install the LinkSocks command-line tool using the Go package manager. ```bash go install github.com/linksocks/linksocks/cmd/linksocks@latest ``` -------------------------------- ### Initialize LinkSocks Server in Go Source: https://linksocks.github.io/go Programmatic setup for a LinkSocks server, including token generation and readiness waiting. ```go package main import ( "context" "log" "time" "github.com/linksocks/linksocks/linksocks" ) func main() { srv := linksocks.NewLinkSocksServer(linksocks.DefaultServerOption()) // Add a forward token (empty string auto-generates) token, err := srv.AddForwardToken("") if err != nil { log.Fatal(err) } log.Printf("Token: %s", token) // Start and wait until ready (30s timeout) if err := srv.WaitReady(context.Background(), 30*time.Second); err != nil { log.Fatal(err) } log.Println("Server ready") // Keep running select {} } ``` -------------------------------- ### Start SOCKS5 Proxy Server Source: https://linksocks.github.io/guide/quick-start Initializes the server on a specified port using a token. ```bash linksocks server -t example_token -r -p 9870 ``` -------------------------------- ### wait_ready Source: https://linksocks.github.io/python/server Starts and waits for the server to be ready. ```APIDOC ## wait_ready(timeout=None) ### Description Starts the server and blocks until it's fully initialized and ready to accept connections. ### Parameters - **timeout** (Optional[DurationLike]) - Optional - Maximum time to wait, no timeout if None ``` -------------------------------- ### Initialize LinkSocks Client in Go Source: https://linksocks.github.io/go Programmatic setup for a LinkSocks client with WebSocket URL and SOCKS port configuration. ```go package main import ( "context" "log" "time" "github.com/linksocks/linksocks/linksocks" ) func main() { opt := linksocks.DefaultClientOption(). WithWSURL("ws://localhost:8765"). WithSocksPort(9870) cli := linksocks.NewLinkSocksClient("your_token", opt) defer cli.Close() // Start and wait until ready (30s timeout) if err := cli.WaitReady(context.Background(), 30*time.Second); err != nil { log.Fatal(err) } log.Println("SOCKS5 ready on 127.0.0.1:9870") select {} } ``` -------------------------------- ### wait_ready(timeout) Source: https://linksocks.github.io/python/client Starts the client and blocks until the connection is fully initialized and ready to proxy traffic. ```APIDOC ## wait_ready(timeout) ### Description Starts the client, establishes the WebSocket connection, and blocks until it is fully initialized. An asynchronous version `async_wait_ready` is also available. ### Parameters - **timeout** (DurationLike) - Optional - Maximum time to wait for initialization. ``` -------------------------------- ### Start Reverse Proxy via CLI Source: https://linksocks.github.io/go Commands to initialize a reverse proxy server, connect a provider client, and verify traffic. ```bash linksocks server -t my_token -p 9870 -r ``` ```bash linksocks client -t my_token -u ws://localhost:8765 -r ``` ```bash curl --socks5 localhost:9870 http://httpbin.org/ip ``` -------------------------------- ### Enable LinkSocks API Source: https://linksocks.github.io/guide/http-api Start the server with the --api-key flag to enable the HTTP API. ```bash linksocks server --api-key your_secret_api_key ``` -------------------------------- ### Start Forward Proxy via CLI Source: https://linksocks.github.io/go Commands to initialize a forward proxy server, connect a client, and verify traffic through the proxy. ```bash linksocks server -t my_token ``` ```bash linksocks client -t my_token -u ws://localhost:8765 -p 9870 ``` ```bash curl --socks5 localhost:9870 http://httpbin.org/ip ``` -------------------------------- ### Use add_reverse_token Source: https://linksocks.github.io/python/server Examples of creating reverse tokens with authentication and connector management settings. ```python server = Server() # Basic reverse token result1 = server.add_reverse_token() print(f"Token: {result1.token}, Port: {result1.port}") # With authentication result2 = server.add_reverse_token( token="secure_token", port=9870, username="proxy_user", password="proxy_pass" ) # With connector management result3 = server.add_reverse_token( allow_manage_connector=True ) ``` -------------------------------- ### Install LinkSocks via pip Source: https://linksocks.github.io/python Use this command to install the LinkSocks package in your Python environment. ```bash pip install linksocks ``` -------------------------------- ### Server Status Response Source: https://linksocks.github.io/guide/http-api Example response from the GET /api/status endpoint. ```json { "version": "3.0.12", "tokens": [ { "token": "forward_token_123", "type": "forward", "clients_count": 2 }, { "token": "reverse_token_456", "type": "reverse", "clients_count": 1, "port": 9870, "connector_tokens": ["connector_abc", "connector_def"] } ] } ``` -------------------------------- ### Enable Fast Open on Server Source: https://linksocks.github.io/guide/fast-open Use the --fast-open flag when starting the LinkSocks server in reverse proxy mode. ```bash # Enable Fast Open on server linksocks server -t token --fast-open ``` -------------------------------- ### Enable Fast Open on Client Source: https://linksocks.github.io/guide/fast-open Use the --fast-open flag when starting the LinkSocks client in forward proxy mode. ```bash # Enable Fast Open on client linksocks client -t token -u ws://server:8765 --fast-open ``` -------------------------------- ### Configure LinkSocks Load Balancing Source: https://linksocks.github.io/guide/load-balancing Start the server and multiple clients in reverse proxy mode to enable connection distribution. ```bash # Server linksocks server -t token -r -p 9870 # Multiple clients linksocks client -t token -r & linksocks client -t token -r & ``` -------------------------------- ### Access Client Properties Source: https://linksocks.github.io/python/client Signatures and usage examples for accessing client properties like logger, connection status, and SOCKS5 port. ```python @property def log(self) -> logging.Logger ``` ```python @property def is_connected(self) -> bool ``` ```python client = Client("token", ws_url="ws://localhost:8765") client.wait_ready() if client.is_connected: print("✅ Client is connected") else: print("❌ Client is disconnected") client.close() ``` ```python @property def socks_port(self) -> Optional[int] ``` ```python # Forward mode client client = Client("token", ws_url="ws://localhost:8765", socks_port=9870) client.wait_ready() print(f"SOCKS5 proxy available at: 127.0.0.1:{client.socks_port}") client.close() ``` -------------------------------- ### Manage Connectors in Reverse Mode Source: https://linksocks.github.io/python/client Method signature and usage example for adding connector tokens in reverse proxy mode. ```python def add_connector(self, connector_token: Optional[str]) -> str ``` ```python # Reverse mode client client = Client("reverse_token", ws_url="ws://localhost:8765", reverse=True) client.wait_ready() # Add connector connector1 = client.add_connector("my_connector") connector2 = client.add_connector(None) # Auto-generated print(f"Connectors: {connector1}, {connector2}") ``` -------------------------------- ### GET /api/status Source: https://linksocks.github.io/guide/http-api Retrieves the current server version and a list of all active tokens, including their types and client counts. ```APIDOC ## GET /api/status ### Description Returns server version and a list of all tokens with their types and active client counts. ### Method GET ### Endpoint /api/status ### Response #### Success Response (200) - **version** (string) - Server version - **tokens** (array) - List of token objects #### Response Example { "version": "3.0.12", "tokens": [ { "token": "forward_token_123", "type": "forward", "clients_count": 2 } ] } ``` -------------------------------- ### Remove Token via URL Path Source: https://linksocks.github.io/guide/http-api Example of removing a token using the DELETE method with a URL path. ```bash curl -X DELETE \ -H "X-API-Key: your_api_key" \ http://localhost:8765/api/token/token_to_remove ``` -------------------------------- ### Initialize and Wait for Client Source: https://linksocks.github.io/python/client Demonstrates client instantiation and waiting for readiness with various timeout configurations. ```python # Create client client = Client("token", ws_url="ws://localhost:8765") # Start client and wait indefinitely client.wait_ready() # Start client with timeout client.wait_ready(timeout=30.0) # 30 seconds client.wait_ready(timeout="1m") # 1 minute ``` -------------------------------- ### Create a LinkSocks Client Source: https://linksocks.github.io/go/library Initialize a client using default settings or a custom configuration object. ```go // Default client client := linksocks.NewLinkSocksClient("token", linksocks.DefaultClientOption()) // Custom configuration opt := linksocks.DefaultClientOption(). WithWSURL("ws://localhost:8765"). WithReverse(false). WithSocksPort(9870). WithReconnect(true). WithThreads(4) client := linksocks.NewLinkSocksClient("token", opt) ``` -------------------------------- ### Create LinkSocks Server Source: https://linksocks.github.io/go/library Initialize a server using default options or a custom configuration builder. ```go // Default server server := linksocks.NewLinkSocksServer(linksocks.DefaultServerOption()) // Custom configuration opt := linksocks.DefaultServerOption(). WithWSHost("0.0.0.0"). WithWSPort(8765). WithSocksHost("127.0.0.1"). WithBufferSize(32768). WithFastOpen(true) server := linksocks.NewLinkSocksServer(opt) ``` -------------------------------- ### Manage Client Lifecycle Source: https://linksocks.github.io/go/library Handle client startup, connection status checks, and graceful shutdown. ```go // Start client and wait for ready ctx := context.Background() if err := client.WaitReady(ctx, 30*time.Second); err != nil { log.Fatal(err) } // Check connection status if client.IsConnected { log.Println("Client is connected") } // Get SOCKS port (forward mode) if port := client.SocksPort; port > 0 { log.Printf("SOCKS5 server on port %d", port) } // Graceful shutdown client.Close() ``` -------------------------------- ### Implement Relay Proxy Components Source: https://linksocks.github.io/go/examples Sets up the server, provider, and connector components for a relay proxy configuration. ```go server := linksocks.NewLinkSocksServer(linksocks.DefaultServerOption()) opts := linksocks.DefaultReverseTokenOptions() opts.Port = 9870 opts.AllowManageConnector = true res, _ := server.AddReverseToken(opts) connectorToken, _ := server.AddConnectorToken("", res.Token) _ = connectorToken ``` ```go opt := linksocks.DefaultClientOption(). WithWSURL("ws://localhost:8765"). WithReverse(true) provider := linksocks.NewLinkSocksClient("provider_token", opt) defer provider.Close() _ = provider.WaitReady(context.Background(), 0) ``` ```go opt := linksocks.DefaultClientOption(). WithWSURL("ws://localhost:8765"). WithSocksPort(1180) connector := linksocks.NewLinkSocksClient("connector_token", opt) defer connector.Close() _ = connector.WaitReady(context.Background(), 0) ``` -------------------------------- ### Use Context Managers Source: https://linksocks.github.io/python/client Demonstrates automatic resource management using both synchronous and asynchronous context managers. ```python # Synchronous context manager with Client("token", ws_url="ws://localhost:8765") as client: client.wait_ready() print(f"Client ready, connected: {client.is_connected}") # Client automatically closed when exiting # Asynchronous context manager async def async_context(): async with Client("token", ws_url="ws://localhost:8765") as client: await client.async_wait_ready() print(f"SOCKS5 port: {client.socks_port}") # Client automatically closed when exiting asyncio.run(async_context()) ``` -------------------------------- ### Initialize Server Instance Source: https://linksocks.github.io/python/server Basic instantiation of the Server class with a specified WebSocket port. ```python from linksocks import Server server = Server(ws_port=8765) ``` -------------------------------- ### Configure Forward Proxy Source: https://linksocks.github.io/ Set up a forward proxy by running the server on the network provider and the client on the local machine. ```bash # Server (WebSockets at port 8765, as network provider) linksocks server -t example_token # Client (SOCKS5 at port 9870) linksocks client -t example_token -u http://localhost:8765 -p 9870 ``` -------------------------------- ### Client Initialization and Lifecycle Source: https://linksocks.github.io/python/client Methods for initializing the client, waiting for readiness, and closing the connection. ```APIDOC ## Client(token, ws_url, reverse=False, socks_port=None) ### Description Initializes a new LinkSocks client instance. ### Methods - **wait_ready(timeout=None)**: Blocks until the client is ready. Supports float (seconds) or string (e.g., '1m') timeouts. - **close()**: Closes the client and cleans up resources. ### Context Manager Support Supports both `with Client(...)` (synchronous) and `async with Client(...)` (asynchronous) for automatic resource management. ``` -------------------------------- ### Configure Relay Proxy with Tokens Source: https://linksocks.github.io/guide/quick-start Sets up a relay server with distinct provider and connector tokens. ```bash linksocks server -t provider_token -c connector_token -p 9870 -r ``` ```bash linksocks provider -t provider_token -u ws://localhost:8765 ``` ```bash linksocks connector -t connector_token -u ws://localhost:8765 -p 1180 ``` ```bash curl --socks5 127.0.0.1:1180 http://httpbin.org/ip ``` -------------------------------- ### Control Server Lifecycle Source: https://linksocks.github.io/go/library Wait for the server to become ready and perform a graceful shutdown. ```go // Start server and wait for ready ctx := context.Background() if err := server.WaitReady(ctx, 30*time.Second); err != nil { log.Fatal(err) } // Graceful shutdown server.Close() ``` -------------------------------- ### Connect as Provider and Test Source: https://linksocks.github.io/guide/quick-start Establishes a provider connection and verifies proxy functionality via curl. ```bash linksocks client -t example_token -u ws://localhost:8765 -r # or: linksocks provider -t example_token -u ws://localhost:8765 ``` ```bash curl --socks5 127.0.0.1:9870 http://httpbin.org/ip ``` -------------------------------- ### Implement a Reverse Proxy Server Source: https://linksocks.github.io/go/examples Initializes a LinkSocks server and adds a reverse token with authentication credentials. ```go package main import ( "context" "log" "time" "github.com/linksocks/linksocks/linksocks" ) func main() { server := linksocks.NewLinkSocksServer(linksocks.DefaultServerOption()) opts := linksocks.DefaultReverseTokenOptions() opts.Port = 9870 opts.Username = "user" opts.Password = "pass" res, err := server.AddReverseToken(opts) if err != nil { log.Fatal(err) } log.Printf("Reverse token: %s, SOCKS5 port: %d", res.Token, res.Port) ctx := context.Background() if err := server.WaitReady(ctx, 30*time.Second); err != nil { log.Fatal(err) } log.Println("Reverse server ready") <-ctx.Done() server.Close() } ``` -------------------------------- ### Server Constructor Source: https://linksocks.github.io/python/server Initializes a new LinkSocks Server instance with configuration for WebSocket and SOCKS5 proxy settings. ```APIDOC ## Server(logger, ws_host, ws_port, socks_host, port_pool, socks_wait_client, buffer_size, api_key, channel_timeout, connect_timeout, connector_wait_provider, fast_open, upstream_proxy, upstream_username, upstream_password) ### Description Initializes the LinkSocks server instance. ### Parameters - **logger** (logging.Logger) - Optional - Python logger instance - **ws_host** (str) - Optional - WebSocket server listen address (default: "0.0.0.0") - **ws_port** (int) - Optional - WebSocket server listen port (default: 8765) - **socks_host** (str) - Optional - SOCKS5 server address (default: "127.0.0.1") - **port_pool** (Any) - Optional - Pool of ports for SOCKS5 servers - **socks_wait_client** (bool) - Optional - Wait for client connections before starting SOCKS5 (default: True) - **buffer_size** (int) - Optional - Buffer size for data transfer (default: 32768) - **api_key** (str) - Optional - API key for HTTP management interface - **channel_timeout** (DurationLike) - Optional - Timeout for WebSocket channels (default: 30.0) - **connect_timeout** (DurationLike) - Optional - Timeout for outbound connections (default: 10.0) - **connector_wait_provider** (DurationLike) - Optional - Connector request wait time (default: 5.0) - **fast_open** (bool) - Optional - Enable TCP Fast Open (default: False) - **upstream_proxy** (str) - Optional - Upstream proxy address - **upstream_username** (str) - Optional - Username for upstream proxy - **upstream_password** (str) - Optional - Password for upstream proxy ``` -------------------------------- ### Configure LinkSocks Performance Options Source: https://linksocks.github.io/go/library Adjust buffer sizes, TCP Fast Open, and timeouts to balance throughput and latency requirements. ```go // High throughput server serverOpt := linksocks.DefaultServerOption(). WithBufferSize(131072). // 128KB buffer WithFastOpen(true). // Reduce RTT WithChannelTimeout(300*time.Second) // Long timeout // High throughput client clientOpt := linksocks.DefaultClientOption(). WithBufferSize(131072). // 128KB buffer WithThreads(8). // Multiple connections WithFastOpen(true). // Reduce RTT WithChannelTimeout(300*time.Second) // Long timeout // Low latency configuration lowLatencyOpt := linksocks.DefaultClientOption(). WithBufferSize(4096). // Small buffer WithFastOpen(true). // Immediate response WithConnectTimeout(2*time.Second) // Quick timeout ``` -------------------------------- ### Asynchronous Client Usage Source: https://linksocks.github.io/python/client Demonstrates the asynchronous workflow including waiting for readiness, adding a connector in reverse mode, and cleaning up resources. ```python import asyncio async def async_client_example(): client = Client("token", ws_url="ws://localhost:8765", reverse=True) try: # Start client asynchronously await client.async_wait_ready(timeout=30.0) print("✅ Client ready!") # Add connector asynchronously (reverse mode) connector = await client.async_add_connector("async_connector") print(f"Connector added: {connector}") # Keep running await asyncio.sleep(3600) except asyncio.TimeoutError: print("❌ Connection timeout") finally: # Clean up resources await client.async_close() asyncio.run(async_client_example()) ``` -------------------------------- ### Deploy Provider via Docker Compose Source: https://linksocks.github.io/guide/quick-start Configuration and startup commands for the provider service. ```yaml services: linksocks-provider: image: jackzzs/linksocks:latest environment: LINKSOCKS_MODE: provider LINKSOCKS_URL: l.zetx.tech LINKSOCKS_CONNECTOR_TOKEN: your_connector_token restart: unless-stopped ``` ```bash docker compose up -d docker compose logs -f linksocks-provider ``` -------------------------------- ### Manage Context and Shutdown Source: https://linksocks.github.io/go/library Use Go contexts to handle timeouts and graceful shutdowns via OS signals. ```go // Create cancellable context ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Use with timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() // Graceful shutdown on signal c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c log.Println("Shutting down...") cancel() }() // Start with context if err := server.WaitReady(ctx, 0); err != nil { if err == context.Canceled { log.Println("Shutdown requested") } else { log.Fatal(err) } } ``` -------------------------------- ### Run LinkSocks via Docker Source: https://linksocks.github.io/guide/quick-start Executes the LinkSocks container to display help information. ```bash docker run --rm -it jackzzs/linksocks --help ``` -------------------------------- ### linksocks.NewLinkSocksServer Source: https://linksocks.github.io/go/library Initializes a new LinkSocks server instance using provided configuration options. ```APIDOC ## func NewLinkSocksServer(opt ServerOption) *Server ### Description Creates a new LinkSocks server instance. Configuration is managed via the ServerOption interface. ### Usage ```go server := linksocks.NewLinkSocksServer(linksocks.DefaultServerOption()) ``` ``` -------------------------------- ### Configure Custom Logging Source: https://linksocks.github.io/go/library Integrate a custom zerolog logger into both client and server instances. ```go import "github.com/rs/zerolog" logger := zerolog.New(os.Stdout).With(). Timestamp(). Str("component", "linksocks"). Logger() // Server with custom logger serverOpt := linksocks.DefaultServerOption().WithLogger(logger) server := linksocks.NewLinkSocksServer(serverOpt) // Client with custom logger clientOpt := linksocks.DefaultClientOption().WithLogger(logger) client := linksocks.NewLinkSocksClient("token", clientOpt) ``` -------------------------------- ### Create a Forward Proxy Source: https://linksocks.github.io/python Sets up a WebSocket server and a client to route traffic through a remote proxy. ```python import asyncio from linksocks import Server, Client async def forward_proxy_example(): # Start server async with Server(ws_port=8765) as server: # Add token for client authentication token = await server.async_add_forward_token() print(f"Created token: {token}") # Start client that provides SOCKS5 proxy async with Client(token, ws_url="ws://localhost:8765", socks_port=9870) as client: print("✅ Forward proxy ready!") print(f"📡 Use SOCKS5 proxy: 127.0.0.1:9870") print("🌐 Example: curl --socks5 127.0.0.1:9870 http://httpbin.org/ip") # Keep running await asyncio.sleep(60) # Run the example asyncio.run(forward_proxy_example()) ``` -------------------------------- ### Deploy Connector via Docker Compose Source: https://linksocks.github.io/guide/quick-start Configuration and startup commands for the connector service. ```yaml services: linksocks-connector: image: jackzzs/linksocks:latest environment: LINKSOCKS_MODE: connector LINKSOCKS_URL: l.zetx.tech LINKSOCKS_TOKEN: your_connector_token ports: - "127.0.0.1:1080:1080" restart: unless-stopped ``` ```bash docker compose up -d curl --socks5 127.0.0.1:1080 http://httpbin.org/ip ``` -------------------------------- ### Initialize LinkSocks Client Source: https://linksocks.github.io/python/client Basic instantiation of the Client class with a token and WebSocket URL. ```python from linksocks import Client client = Client("your_token", ws_url="ws://localhost:8765") ``` -------------------------------- ### Server Constructor Signature Source: https://linksocks.github.io/python/server Full parameter list for the Server class constructor. ```python Server( *, logger: Optional[logging.Logger] = None, ws_host: Optional[str] = None, ws_port: Optional[int] = None, socks_host: Optional[str] = None, port_pool: Optional[Any] = None, socks_wait_client: Optional[bool] = None, buffer_size: Optional[int] = None, api_key: Optional[str] = None, channel_timeout: Optional[DurationLike] = None, connect_timeout: Optional[DurationLike] = None, connector_wait_provider: Optional[DurationLike] = None, fast_open: Optional[bool] = None, upstream_proxy: Optional[str] = None, upstream_username: Optional[str] = None, upstream_password: Optional[str] = None, ) ``` -------------------------------- ### Use server context managers Source: https://linksocks.github.io/python/server Manages server lifecycle automatically using synchronous or asynchronous context managers. ```python # Synchronous context manager with Server() as server: server.add_forward_token("context_token") server.wait_ready() print("Server ready in context") # Server automatically closed when exiting context # Asynchronous context manager async def async_context(): async with Server() as server: server.add_forward_token("async_context") await server.async_wait_ready() print("Server ready in async context") # Server automatically closed when exiting context asyncio.run(async_context()) ``` -------------------------------- ### Client Constructor Signature Source: https://linksocks.github.io/python/client Full parameter list for the Client constructor, allowing configuration of proxy settings, timeouts, and connection behavior. ```python Client( token: str, *, logger: Optional[logging.Logger] = None, ws_url: Optional[str] = None, reverse: Optional[bool] = None, socks_host: Optional[str] = None, socks_port: Optional[int] = None, socks_username: Optional[str] = None, socks_password: Optional[str] = None, socks_wait_server: Optional[bool] = None, reconnect: Optional[bool] = None, reconnect_delay: Optional[DurationLike] = None, buffer_size: Optional[int] = None, channel_timeout: Optional[DurationLike] = None, connect_timeout: Optional[DurationLike] = None, threads: Optional[int] = None, fast_open: Optional[bool] = None, upstream_proxy: Optional[str] = None, upstream_username: Optional[str] = None, upstream_password: Optional[str] = None, no_env_proxy: Optional[bool] = None, ) ``` -------------------------------- ### Client Constructor Source: https://linksocks.github.io/python/client Initializes a new LinkSocks Client instance with the specified configuration for WebSocket and SOCKS5 proxy settings. ```APIDOC ## Client(token, ...) ### Description Initializes the LinkSocks client. This constructor accepts various configuration parameters to define the WebSocket connection, SOCKS5 server settings, and proxy behavior. ### Parameters - **token** (str) - Required - Authentication token for WebSocket connection. - **logger** (logging.Logger) - Optional - Python logger instance. - **ws_url** (str) - Optional - WebSocket server URL (default: "ws://localhost:8765"). - **reverse** (bool) - Optional - Enable reverse proxy mode (default: False). - **socks_host** (str) - Optional - SOCKS5 server address (default: "127.0.0.1"). - **socks_port** (int) - Optional - SOCKS5 server port (default: 9870). - **socks_username** (str) - Optional - SOCKS5 authentication username. - **socks_password** (str) - Optional - SOCKS5 authentication password. - **socks_wait_server** (bool) - Optional - Wait for server before starting SOCKS5 (default: True). - **reconnect** (bool) - Optional - Auto-reconnect on disconnect (default: True). - **reconnect_delay** (DurationLike) - Optional - Delay between reconnection attempts (default: 5.0). - **buffer_size** (int) - Optional - Buffer size for data transfer (default: 32768). - **channel_timeout** (DurationLike) - Optional - Timeout for WebSocket channels (default: 30.0). - **connect_timeout** (DurationLike) - Optional - Timeout for outbound connections (default: 10.0). - **threads** (int) - Optional - Number of threads for processing (default: 1). - **fast_open** (bool) - Optional - Fast Open: immediate SOCKS5 success (default: False). - **upstream_proxy** (str) - Optional - Upstream proxy address. - **upstream_username** (str) - Optional - Username for upstream proxy. - **upstream_password** (str) - Optional - Password for upstream proxy. - **no_env_proxy** (bool) - Optional - Ignore proxy environment variables (default: False). ``` -------------------------------- ### Perform Asynchronous Server Operations Source: https://linksocks.github.io/python/server Demonstrates the use of async-prefixed methods for token management and server lifecycle control. ```python import asyncio async def async_server_example(): server = Server() # All async token operations token = await server.async_add_forward_token("async_token") result = await server.async_add_reverse_token(port=9870) success = await server.async_remove_token(token) # Start server asynchronously await server.async_wait_ready(timeout=30.0) print("Server ready!") # Cleanup await server.async_close() asyncio.run(async_server_example()) ``` -------------------------------- ### Import LinkSocks Package Source: https://linksocks.github.io/go/library Import the package to access the LinkSocks API. ```go import "github.com/linksocks/linksocks/linksocks" ``` -------------------------------- ### Server Lifecycle and Status Source: https://linksocks.github.io/go/library Methods for controlling server startup, shutdown, and monitoring connection status. ```APIDOC ## Server Lifecycle ### WaitReady(ctx context.Context, timeout time.Duration) error Starts the server and waits until it is ready or the timeout is reached. ### Close() Performs a graceful shutdown of the server. ## Server Status ### GetClientCount() int Returns the total number of active client connections. ### HasClients() bool Returns true if there are active client connections. ### GetTokenClientCount(token string) int Returns the number of active clients associated with a specific token. ``` -------------------------------- ### Implement Error Handling and Retries Source: https://linksocks.github.io/go/library Handle initialization errors and implement custom retry logic for connection attempts. ```go // Server error handling server := linksocks.NewLinkSocksServer(opt) // Add tokens with error checking if token, err := server.AddForwardToken(""); err != nil { log.Printf("Failed to add token: %v", err) } else { log.Printf("Token added: %s", token) } // Client error handling client := linksocks.NewLinkSocksClient("token", opt) // Connection with retry logic for attempts := 0; attempts < 3; attempts++ { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) err := client.WaitReady(ctx, 0) cancel() if err == nil { break // Success } log.Printf("Connection attempt %d failed: %v", attempts+1, err) if attempts < 2 { time.Sleep(5 * time.Second) } } ``` -------------------------------- ### Enable Debug Logging Source: https://linksocks.github.io/guide/quick-start Run server or client with verbose debug output. ```bash linksocks server -t token -d linksocks client -t token -u ws://localhost:8765 -d ``` -------------------------------- ### Set Custom Listen Addresses Source: https://linksocks.github.io/guide/quick-start Bind server or client to specific network interfaces and ports. ```bash # Server WebSocket on all interfaces linksocks server -t token -H 0.0.0.0 -P 8765 # Client custom SOCKS address linksocks client -t token -u ws://localhost:8765 -h 0.0.0.0 -p 1080 ``` -------------------------------- ### Configure Reverse Proxy Source: https://linksocks.github.io/guide/cli-options Sets up a reverse proxy configuration using the server and client or provider commands. ```bash linksocks server -t my_token -r -p 9870 linksocks client -t my_token -u ws://localhost:8765 -r # or: linksocks provider -t my_token -u ws://localhost:8765 ``` -------------------------------- ### Use Public Relay Server Source: https://linksocks.github.io/guide/quick-start Connects to the public l.zetx.tech relay without hosting a server. ```bash linksocks provider -t any_token -u wss://l.zetx.tech -c your_token ``` ```bash linksocks connector -t your_token -u wss://l.zetx.tech -p 1080 ``` ```bash curl --socks5 127.0.0.1:1080 http://httpbin.org/ip ``` -------------------------------- ### Configure Reverse Proxy Source: https://linksocks.github.io/ Set up a reverse proxy where the server acts as the SOCKS endpoint and the client acts as the network provider. ```bash # Server (WebSockets at port 8765, SOCKS at port 9870) linksocks server -t example_token -p 9870 -r # Client (as network provider) linksocks client -t example_token -u http://localhost:8765 -r ``` -------------------------------- ### NewLinkSocksClient Source: https://linksocks.github.io/go/library Initializes a new LinkSocks client with a provided token and configuration options. ```APIDOC ## func NewLinkSocksClient(token string, opt ClientOption) *Client ### Description Creates a new instance of the LinkSocks client. The client can be configured using the provided `ClientOption`. ### Parameters - **token** (string) - Required - Authentication token for the LinkSocks server. - **opt** (ClientOption) - Required - Configuration options for the client, generated via `DefaultClientOption()`. ``` -------------------------------- ### Create a Reverse Proxy Source: https://linksocks.github.io/python Configures a server to provide a SOCKS5 proxy that allows a remote client to access the internet. ```python import asyncio from linksocks import Server, Client async def reverse_proxy_example(): # Start server async with Server(ws_port=8765) as server: # Create reverse token - server provides SOCKS5 proxy result = await server.async_add_reverse_token() print(f"Created reverse token: {result.token}") print(f"📡 SOCKS5 proxy available at: 127.0.0.1:{result.port}") # Client connects and provides internet access async with Client(result.token, ws_url="ws://localhost:8765", reverse=True) as client: print("✅ Reverse proxy ready!") print("🌐 Example: curl --socks5 127.0.0.1:{} http://httpbin.org/ip".format(result.port)) # Keep running await asyncio.sleep(60) # Run the example asyncio.run(reverse_proxy_example()) ``` -------------------------------- ### Configure SOCKS Authentication Source: https://linksocks.github.io/guide/quick-start Set username and password credentials for SOCKS proxy access. ```bash linksocks server -t token -r -p 9870 -n username -w password linksocks client -t token -u ws://localhost:8765 -n username -w password ``` -------------------------------- ### Implement a Reverse Proxy Provider Client Source: https://linksocks.github.io/go/examples Configures a client to connect to a LinkSocks server using a reverse token and WebSocket URL. ```go package main import ( "context" "log" "time" "github.com/linksocks/linksocks/linksocks" ) func main() { opt := linksocks.DefaultClientOption(). WithWSURL("ws://localhost:8765"). WithReverse(true) client := linksocks.NewLinkSocksClient("reverse_token", opt) defer client.Close() ctx := context.Background() if err := client.WaitReady(ctx, 30*time.Second); err != nil { log.Fatal(err) } log.Println("Provider client ready") <-ctx.Done() } ``` -------------------------------- ### wait_ready(timeout=None) Source: https://linksocks.github.io/python/server Blocks execution until the server is ready. An optional timeout can be provided as a float (seconds) or a string (e.g., '1m'). ```APIDOC ## wait_ready(timeout=None) ### Description Blocks execution until the server is ready. An optional timeout can be provided as a float (seconds) or a string (e.g., '1m'). ### Parameters - **timeout** (float|str) - Optional - The duration to wait for the server to become ready. ``` -------------------------------- ### Optimize Linux UDP Buffer Source: https://linksocks.github.io/guide/quick-start Increase system UDP buffer limits to improve QUIC performance. ```bash sudo sysctl -w net.core.rmem_max=2500000 sudo sysctl -w net.core.wmem_max=2500000 ``` -------------------------------- ### Manage Server Tokens Source: https://linksocks.github.io/go/library Add or remove forward, reverse, and connector tokens for proxy authentication and management. ```go // Forward proxy token token, err := server.AddForwardToken("custom_token") // or "" for auto-gen if err != nil { log.Fatal(err) } // Reverse proxy token opts := linksocks.DefaultReverseTokenOptions() opts.Port = 9870 opts.Username = "user" opts.Password = "pass" opts.AllowManageConnector = false result, err := server.AddReverseToken(opts) if err != nil { log.Fatal(err) } log.Printf("Token: %s, Port: %d", result.Token, result.Port) // Connector token (for relay proxy) connectorToken, err := server.AddConnectorToken("connector_token", "reverse_token") if err != nil { log.Fatal(err) } // Remove any token removed := server.RemoveToken("token_to_remove") ``` -------------------------------- ### wait_ready Method Signature Source: https://linksocks.github.io/python/client Definition of the wait_ready method used to block until the client is fully initialized. ```python def wait_ready(self, timeout: Optional[DurationLike] = None) -> None ``` -------------------------------- ### Add Forward Tokens Source: https://linksocks.github.io/python/server Demonstrates generating forward tokens with either automatic or custom naming. ```python # Auto-generate token token1 = server.add_forward_token() print(f"Generated: {token1}") # Use specific token token2 = server.add_forward_token("my_custom_token") print(f"Custom: {token2}") ``` -------------------------------- ### Wait for server readiness Source: https://linksocks.github.io/python/server Blocks execution until the server is ready, optionally accepting a timeout in seconds or as a string duration. ```python # Start server and wait indefinitely server.wait_ready() # Start server with timeout server.wait_ready(timeout=30.0) # 30 seconds server.wait_ready(timeout="1m") # 1 minute ``` -------------------------------- ### Generate Production Tokens Source: https://linksocks.github.io/guide/authentication Generate strong random tokens for production environments using system utilities. ```bash openssl rand -hex 16 ``` ```powershell [System.Web.Security.Membership]::GeneratePassword(32, 8) ``` -------------------------------- ### Configure SOCKS5 Credentials Source: https://linksocks.github.io/guide/authentication Set optional username and password authentication on the SOCKS5 interface for different proxy modes. ```bash # Forward mode - client provides SOCKS5 server linksocks client -t token -u ws://localhost:8765 -p 9870 -n user -w pass # Reverse mode - server provides SOCKS5 server linksocks server -t token -r -p 9870 -n user -w pass # Relay proxy - connector provides SOCKS5 server linksocks connector -t connector_token -p 9870 -r -n user -w pass ``` -------------------------------- ### Configure Regular Relay Proxy Tokens Source: https://linksocks.github.io/guide/authentication Manage provider and connector tokens centrally on the server for regular relay proxy mode. ```bash # Server sets both Provider Token and Connector Token linksocks server -t provider_token -c connector_token -p 9870 -r ``` ```bash # Provider uses the Provider Token set by server linksocks provider -t provider_token -u ws://localhost:8765 ``` ```bash # Connector uses the Connector Token set by server linksocks connector -t connector_token -u ws://localhost:8765 -p 1180 ``` -------------------------------- ### Access server logger Source: https://linksocks.github.io/python/server Retrieves the logger instance or configures a custom logger for the server. ```python @property def log(self) -> logging.Logger ``` ```python import logging # Custom logger logger = logging.getLogger("my_server") logger.setLevel(logging.DEBUG) server = Server(logger=logger) server.log.info("Server created") # Uses custom logger ``` -------------------------------- ### Client Properties Source: https://linksocks.github.io/python/client Properties to monitor client state and configuration. ```APIDOC ## Client Properties ### log - **Type**: logging.Logger - **Description**: Access the Python logger instance for this client. ### is_connected - **Type**: bool - **Description**: Check if the client is currently connected to the server. ### socks_port - **Type**: Optional[int] - **Description**: Get the SOCKS5 server port (forward mode only). ``` -------------------------------- ### Manage Connectors in Reverse Mode Source: https://linksocks.github.io/go/library Add or remove connectors and retrieve partner counts when operating in reverse proxy mode. ```go // Add connector (reverse mode only) connectorToken, err := client.AddConnector("custom_connector") // or "" for auto-gen if err != nil { log.Fatal(err) } // Remove connector (reverse mode only) err = client.RemoveConnector("connector_token") if err != nil { log.Fatal(err) } // Get partners count partnersCount := client.GetPartnersCount() ``` -------------------------------- ### Configure Self-Managed Connector Tokens Source: https://linksocks.github.io/guide/authentication Allow providers to define their own connector tokens for isolated provider-connector pairs. ```bash # Server only sets Provider Token, no Connector Token needed linksocks server -t provider_token -r -a ``` ```bash # Provider connects with Provider Token and defines custom Connector Token linksocks provider -t provider_token -c my_custom_connector_token -u ws://localhost:8765 ``` ```bash # Connector uses the provider's custom token linksocks connector -t my_custom_connector_token -u ws://localhost:8765 -p 1180 ``` -------------------------------- ### Configure Relay Proxy with Self-Managed Connectors Source: https://linksocks.github.io/guide/cli-options Configures a relay proxy where providers register their own connector tokens. ```bash linksocks server -t provider_token -r -a linksocks provider -t provider_token -c my_connector_token -u ws://localhost:8765 linksocks connector -t my_connector_token -u ws://localhost:8765 -p 1180 ``` -------------------------------- ### Token Management Methods Source: https://linksocks.github.io/go/library Methods for managing forward, reverse, and connector tokens on the server instance. ```APIDOC ## Token Management ### AddForwardToken(token string) (string, error) Adds a forward proxy token. Pass an empty string for auto-generation. ### AddReverseToken(opts ReverseTokenOptions) (ReverseTokenResult, error) Adds a reverse proxy token with specific port and authentication settings. ### AddConnectorToken(token string, reverseToken string) (string, error) Adds a connector token for relay proxy functionality. ### RemoveToken(token string) bool Removes an existing token from the server. ``` -------------------------------- ### Client Lifecycle Methods Source: https://linksocks.github.io/go/library Methods for managing the connection state and lifecycle of the LinkSocks client. ```APIDOC ## Client Lifecycle Methods ### WaitReady(ctx context.Context, timeout time.Duration) error Starts the client and waits for the connection to be ready. Returns an error if the connection fails or times out. ### Close() Gracefully shuts down the client connection. ### IsConnected (Field) A boolean indicating the current connection status of the client. ``` -------------------------------- ### Basic API Usage Source: https://linksocks.github.io/guide/http-api Perform common operations like checking status and managing tokens using curl. ```bash # Get server status curl -H "X-API-Key: your_secret_api_key" \ http://localhost:8765/api/status # Add a forward token curl -X POST \ -H "X-API-Key: your_secret_api_key" \ -H "Content-Type: application/json" \ -d '{"type":"forward","token":"my_token"}' \ http://localhost:8765/api/token # Remove a token curl -X DELETE \ -H "X-API-Key: your_secret_api_key" \ http://localhost:8765/api/token/my_token ``` -------------------------------- ### Configure Direct Transport Source: https://linksocks.github.io/guide/cli-options Enables direct transport mode for server and client communication. ```bash linksocks server -t my_token --direct-enable linksocks client -t my_token -u ws://localhost:8765 --direct-mode auto ``` -------------------------------- ### Connection Management Message Structures Source: https://linksocks.github.io/guide/message-protocol Defines the binary layout for establishing, responding to, and closing proxy connections. ```text Version(1) + Type(1) + Protocol(1) + ChannelID(16) + [AddrLen(1) + Addr(N) + Port(2) if TCP] ``` ```text Version(1) + Type(1) + Success(1) + ChannelID(16) + [ErrorLen(1) + Error(N) if !Success] ``` ```text Version(1) + Type(1) + ChannelID(16) + [ErrorLen(1) + Error(N) if error] ``` -------------------------------- ### Monitor Server Status Source: https://linksocks.github.io/go/library Retrieve information about active client connections and token-specific usage. ```go // Check client connections clientCount := server.GetClientCount() hasClients := server.HasClients() // Check token-specific clients tokenClients := server.GetTokenClientCount("specific_token") ``` -------------------------------- ### Configure WebSocket Tokens Source: https://linksocks.github.io/guide/authentication Set tokens for client-server authentication in forward and reverse proxy modes. The 'anonymous' token is reserved for clients that do not specify a token. ```bash # Server (auto-generate if omitted) linksocks server -t server_token # Client (uses 'anonymous' if omitted) linksocks client -t server_token -u ws://localhost:8765 # Client with anonymous token (no -t flag needed) linksocks client -u ws://localhost:8765 ``` -------------------------------- ### API Authentication Header Source: https://linksocks.github.io/guide/http-api Include the X-API-Key header in all requests. ```http X-API-Key: your_secret_api_key ``` -------------------------------- ### Add Forward Token Method Signature Source: https://linksocks.github.io/python/server Method signature for adding a forward proxy token. ```python def add_forward_token(self, token: Optional[str] = None) -> str ```