Last active
          November 14, 2024 09:11 
        
      - 
      
- 
        Save mval1/37400de66da1a43227242f73f4a15fd1 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | using System; | |
| using System.Net.WebSockets; | |
| using System.Text; | |
| using System.Threading; | |
| using System.Threading.Tasks; | |
| public class WebSocketClient | |
| { | |
| private readonly Uri _serverUri; | |
| private readonly string _bearerToken; | |
| private ClientWebSocket _client; | |
| public WebSocketClient(string serverUrl, string bearerToken) | |
| { | |
| _serverUri = new Uri(serverUrl); | |
| _bearerToken = bearerToken; | |
| _client = new ClientWebSocket(); | |
| } | |
| public async Task ConnectAsync() | |
| { | |
| // Добавляем токен Bearer в заголовок | |
| _client.Options.SetRequestHeader("Authorization", $"Bearer {_bearerToken}"); | |
| try | |
| { | |
| await _client.ConnectAsync(_serverUri, CancellationToken.None); | |
| Console.WriteLine("Connected to the server."); | |
| // Начинаем слушать сообщения от сервера | |
| await ReceiveMessagesAsync(); | |
| } | |
| catch (Exception ex) | |
| { | |
| Console.WriteLine($"Connection failed: {ex.Message}"); | |
| } | |
| } | |
| private async Task ReceiveMessagesAsync() | |
| { | |
| var buffer = new byte[1024 * 4]; | |
| while (_client.State == WebSocketState.Open) | |
| { | |
| var result = await _client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); | |
| if (result.MessageType == WebSocketMessageType.Text) | |
| { | |
| // Обрабатываем команду | |
| string message = Encoding.UTF8.GetString(buffer, 0, result.Count); | |
| Console.WriteLine($"Received message: {message}"); | |
| // Если выполнение команды успешно, отправляем ответ | |
| string response = ProcessCommand(message); | |
| if (!string.IsNullOrEmpty(response)) | |
| { | |
| await SendMessageAsync(response); | |
| } | |
| } | |
| else if (result.MessageType == WebSocketMessageType.Close) | |
| { | |
| Console.WriteLine("Server closed connection."); | |
| await _client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None); | |
| } | |
| } | |
| } | |
| private string ProcessCommand(string command) | |
| { | |
| // Логика обработки команды | |
| // Например, выполнение какой-то операции в зависимости от команды | |
| Console.WriteLine($"Processing command: {command}"); | |
| // Возвращаем результат или подтверждение | |
| return $"Command '{command}' processed successfully."; | |
| } | |
| private async Task SendMessageAsync(string message) | |
| { | |
| var messageBuffer = Encoding.UTF8.GetBytes(message); | |
| await _client.SendAsync(new ArraySegment<byte>(messageBuffer), WebSocketMessageType.Text, true, CancellationToken.None); | |
| Console.WriteLine($"Sent message: {message}"); | |
| } | |
| public async Task DisconnectAsync() | |
| { | |
| if (_client.State == WebSocketState.Open) | |
| { | |
| await _client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client disconnecting", CancellationToken.None); | |
| } | |
| _client.Dispose(); | |
| Console.WriteLine("Disconnected from the server."); | |
| } | |
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | public class Program | |
| { | |
| public static async Task Main(string[] args) | |
| { | |
| string serverUrl = "wss://yourserver.com/websocket"; | |
| string bearerToken = "your_bearer_token"; | |
| var client = new WebSocketClient(serverUrl, bearerToken); | |
| await client.ConnectAsync(); | |
| Console.WriteLine("Press any key to disconnect..."); | |
| Console.ReadKey(); | |
| await client.DisconnectAsync(); | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment