How to send a message to Specific Destination through ClientWebSocket in .Net
I have a WebSocket server written in Java and I need to create a Client in .Net I am using .Net Library System.Net.WebSockets However the server expects the message to be sent to a specific destination some thing like(/app/message). However through websocket.Send method I can only pass the actual message. (ex in java stompSession.send("/app/destination", "actual Message"))
How Can I send a message to specific destination using ClientWebSocket.
var socket =new ClientWebSocket();
socket.ConnectAsync(new Uri("ws://example"), CancellationToken.None).Wait();
var data = System.Text.Encoding.UTF8.GetBytes("Hi from Client!");
var si = socket.SendAsync(data, WebSocketMessageType.Text,true,CancellationToken.None);
Console.WriteLine("Sent");
var byt = new byte[4096];
var response = new ArraySegment<byte>(byt);
var res = socket.ReceiveAsync(response, CancellationToken.None);
var responseText = System.Text.Encoding.UTF8.GetString(response);
Console.WriteLine(responseText);
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
site only opens in CefSharp
zaakr.net is a site can be opened only in zaakr.exe application or through android(.apk), when opened in browser u been redirected to https://browser.zaakr.net so u download there application, (.exe) file is using cefsharp as a browser so it can access website, from 2 month i could open it from chromium as cefsharp uses chromium, now i can't access website through chromium for some reason idk, i even made a cefsharp browser myself using visual studio nothing worked all the time i been redirected to browser.zaakr.com, i want to access through any browser that have devtools available for a project, note that application zaakr.exe is still using cefsharp even the older version still can access site. i would appreciate any help, sry for any spelling mistakes, thanks.
-
C# MariaDB Update Function working in DataStore but not updating in .NET Application
My initial issue is that my database does not update when I call on this specific code. I am not sure if it is C# itself or the update query that I am calling.
string _connectionString = "validConnectionstring"; using (MySqlConnection _mySqlConnection = new MySqlConnection(_connectionString) { _mySqlConnection.Open(); using (MySqlCommand command = new MySqlCommand("UpdateProfileStatus", _mySqlConnection)) { command.Transaction = _mySqlConnection.BeginTransaction(); command.CommandTimeout = TimeSpan.FromSeconds(60).Seconds; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@_username", "test"); command.Parameters.AddWithValue("@_status", true); command.ExecuteNonQuery(); } _mySqlConnection.Close(); }
I get no updates in my database but my console logs that the query is executed returning the value of 1 but there is no update that actually happens in my DB. Is there something in my code to reason why it is failing?
Here is the stored procedure that I have for the update command
CREATE PROCEDURE UpdateProfileStatus(_username VARCHAR(25), _status BOOL) UPDATE Profile SET status = _status WHERE username = _username;
I know the Stored Procedure works but am not sure why my .NET application is not responding to my procedure call. Is it something to do with my implementation of the parameters or is it my procedure itself?
-
How to add a new Model visually in Mac OS visual Studio
I do not see any choice to create a model in Mac visual studio? I In the windows version the Class created with its imports
using Linq
using Threading.Tasks
using Collection.Generic
-
Using Websocket Channel in React
I am working on a project where I have to make an api call to a websocket, and display certain information based on that call. As you can see I have used the subscribe portion of the channel in my call. Now I'm not sure what to do if anything with the 2nd two set of bracket. Do I need to include them my call as well, or do they come along with the subscription? And from which of them would I be using the information I need to display? In other words which one is the information I am recieving?
'''
const ws = new WebSocket("wss://ws-feed.exchange.coinbase.com"); const apiCall = { type: "subscribe", product_ids: [ "ETH-USD", "BTC-USD" ], channels: ["level2"] }; ws.onopen = (event) => { ws.send(JSON.stringify(apiCall)); }; ws.onmessage = function (event) { const json = JSON.parse(event.data); console.log(`[message] Data received from server: ${json}`); };
'''
-
Websocket with special characters
I am using websocket with client nodejs and server golang (net library) via tcp. I am read data sent from client but many special chars. Some one can help me about that?
Data received:
\u0016\u0003\u0001\u0002\u0000\u0001\u0000\u0001\ufffd\u0003\u0003x\ufffd_\ufffdj\ufffd\ufffd\ufffd\ufffdȬ{\ufffd \ufffdI\u003c9\u000bC1YŲ\ufffdVp\u0017\ufffd\u000e`\ufffd \ufffd\ufffd\ufffd\u0017\ufffd\ufffd=\\u0002\ufffd~,\u0011\ufffdn\ufffd\ufffdY\u0010\ufffd\u001c\ufffdw\u000f\ufffd\ufffd(hfK\ufffd\ufffd\u0000 \u001a\u001a\u0013\u0001\u0013\u0002\u0013\u0003\ufffd+\ufffd/\ufffd,\ufffd0̨̩\ufffd\u0013\ufffd\u0014\u0000\ufffd\u0000\ufffd\u0000/\u00005\u0001\u0000\u0001\ufffd\ufffd\ufffd\u0000\u0000\u0000\u0000\u0000\u0014\u0000\u0012\u0000\u0000\u000fvenus.localhost\u0000\u0017\u0000\u0000\ufffd\u0001\u0000\u0001\u0000\u0000"
This func use to accept tcp
func (s *WebsocketServer) Serve() { if s.running { return } s.running = true for _, lsn := range s.lsnList { for i := 0; i < s.accepts; i++ { go func(lsn2 *net.TCPListener) { var ( conn *net.TCPConn err error ) for { if conn, err = AcceptTCP(lsn2); err != nil { // if listener close then return log.Error("listener.Accept(\"%s\") error(%v)", lsn2.Addr().String(), err) return } if err = conn.SetKeepAlive(s.c.Keepalive); err != nil { log.Error("conn.SetKeepAlive() error(%v)", err) return } if err = conn.SetReadBuffer(s.c.ReceiveBuf); err != nil { log.Error("conn.SetReadBuffer() error(%v)", err) return } if err = conn.SetWriteBuffer(s.c.SendBuf); err != nil { log.Error("conn.SetWriteBuffer() error(%v)", err) return } go s.establishWebsocketConnection(conn) } }(lsn) } } } func (s *WebsocketServer) establishWebsocketConnection(conn net.Conn) { var ( // conn2 = NewBufferedConnSize(conn, 66560) req *websocket.Request websocketConn *websocket.Conn err error ) rr := bufio.NewReader(conn) if req, err = websocket.ReadRequest(rr); err != nil || req.RequestURI != "/apiws" { conn.Close() if err != io.EOF { log.Errorf("websocket.ReadRequest(rr) error(%v)", err) } return } else { wr := bufio.NewWriter(conn) websocketConn, err = websocket.Upgrade(conn, rr, wr, req) if err != nil { log.Errorf("websocket.Upgrade(rr) error(%v)", err) conn.Close() return } } codec, err := NewCodecByName(s.c.ProtoName, websocketConn) tcpConn := NewTcpConnection2(s.c.ServerName, websocketConn, s.c.SendChanSize, codec, true, s) // log.Info("establishTcpConnection...") defer func() { if err := recover(); err != nil { log.Error("tcp_server handle panic: %v\n%s", err, debug.Stack()) tcpConn.Close() } }() s.onNewConnection(tcpConn) for { tcpConn.conn.SetReadDeadline(time.Now().Add(time.Minute * 6)) msg, err := tcpConn.Receive() if err != nil { log.Error("conn: %s recv error: %v", tcpConn, err) return } if msg == nil { log.Error("recv a nil msg by conn: %s", tcpConn) continue } if s.callback != nil { // log.Info("onConnectionDataArrived - conn: %s", conn) if err := s.callback.OnConnectionDataArrived(tcpConn, msg); err != nil { } } } }
Function from websocket file, I print data here like above
func ReadRequest(r *bufio.Reader) (req *Request, err error) { var ( b []byte ok bool ) req = &Request{reader: r} if b, err = req.readLine(); err != nil { return } log.Errorf("websocket.ReadRequest: %s", string(b)) if req.Method, req.RequestURI, req.Proto, ok = parseRequestLine(string(b)); !ok { return nil, fmt.Errorf("malformed HTTP request %s", b) } if req.Header, err = req.readMIMEHeader(); err != nil { return } req.Host = req.Header.Get("Host") return req, nil } func (r *Request) readLine() ([]byte, error) { var line []byte for { l, more, err := r.reader.ReadLine() if err != nil { return nil, err } // Avoid the copy if the first call produced a full line. if line == nil && !more { return l, nil } line = append(line, l...) if !more { break } } return line, nil }
Please help me
-
How to maintain a Websocket connection for my Angular(13.0.4) application across pages? I need to load the websocket url into service not at the start
So this is my web-socket.service.ts where I send the url information to the websocket in order to establish the connection:
import { Injectable } from '@angular/core'; import { Observable, Observer, Subject } from 'rxjs'; import { AnonymousSubject } from 'rxjs/internal/Subject'; import { Message } from './ws-message.type' import { Router} from '@angular/router'; @Injectable({ providedIn: 'root' }) export class WebSocketService { private subject: AnonymousSubject<MessageEvent>; public messages: Subject<Message>; private jwt: string; constructor(private router: Router) { } public connect(url): AnonymousSubject<MessageEvent> { if (!this.subject) { this.subject = this.create(url); console.log("Successfully connected: " + url); } return this.subject; } private create(url): AnonymousSubject<MessageEvent> { let ws = new WebSocket(url); let observable = new Observable((obs: Observer<MessageEvent>) => { ws.onmessage = obs.next.bind(obs); ws.onerror = obs.error.bind(obs); ws.onclose = obs.complete.bind(obs); return ws.close.bind(ws); }); let observer = { error: null, complete: null, next: (data: Object) => { console.log('Message sent to websocket: ', data); if (ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify(data)); } } }; return new AnonymousSubject<MessageEvent>(observer, observable); } }
Currently I make the connection on my typescript by:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { environment } from 'src/environments/environment'; import { webSocket } from 'rxjs/webSocket'; import { MenuController } from '@ionic/angular'; @Component({ selector: 'app-org', templateUrl: './org.page.html', styleUrls: ['./org.page.scss'], }) export class OrgPage implements OnInit { jwt: string; ws_session; stringObject: any; stringJson: any; content:any = []; constructor(public menuCtrl: MenuController, private router: Router) { this.jwt = sessionStorage.getItem("jwt"); if (this.jwt) { this.ws_session = webSocket(environment.WS_API_URL + '/connect/' + this.jwt); this.ws_session.subscribe(msg => { if (msg.action == "get_my_orgs"){ this.content = Object.assign(msg.content); this.stringJson = JSON.stringify(this.content); this.stringObject = JSON.parse(this.stringJson); console.log("JSON object -", this.stringObject); } }); } }
The connection currently works, but I create a new connection every page. I only want one connection across all pages as soon as I make the call to establish the connection. I'd like to know how to close the connection as well.
-
Spring Boot Security with JWT Authentification and STOMP Websockets. STOMP Endpoint responding 404 to React frontend
when iam adding the Spring Boot Starter Security dependency on my Projekt my STOMP Endpoint responding an 404 Code to my React frontend. I build a simple Demo Projekt with only web socket dependency. In this case everything works fine. When iam adding the security dependency without any configuration i get a 403. At this point everything is fine. When iam adding the same WebSecurityConfigurerAdapter implementation as the Main Projekt everything works fine aswell. But on my main Projekt it did not work. Everytime i get a 404 on my endpoint
ws://localhost:8080/socket
I tried to get this work for one Week now... I cant figure it out where i should configure the Security part for the SocketsThe goul of all this is to stream progress information of some Tasks to the frontend. If you have any other solutions to build that i would be happy. It could be that websockets are not the best way to do that.
and btw. its my first Question on Stackoverflow please dont judge me if the formatting is not the best way :-)
Iam storing the User Informations in a h2 Database.
Here my Configurations and Dependencys for the Backend
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j2 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> <version>2.6.6</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.0</version> </dependency>
The WebSecurityConfigurerAdapter implementation
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { private final AppUserDetailService appUserDetailService; private final Filter jwtAuthFilter; @Autowired public SecurityConfig(AppUserDetailService appUserDetailService, Filter jwtAuthFilter){ this.appUserDetailService = appUserDetailService; this.jwtAuthFilter = jwtAuthFilter; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(appUserDetailService); } @Override protected void configure(HttpSecurity http) throws Exception { .antMatchers("/auth/**","/oauth/**", "/topic/**", "/socket/**", "/app/**").permitAll() .antMatchers("/api/**").authenticated() .antMatchers("/**").permitAll().and() .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception{ return super.authenticationManagerBean(); } }
JWTAuthFilter
@Slf4j @Component public class JwtAuthFilter extends OncePerRequestFilter { private final JWTUtilService jwtUtil; public JwtAuthFilter(JWTUtilService jwtUtil) { this.jwtUtil = jwtUtil; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = getAuthToken(request); try{ if(token != null && !token.isBlank()){ String username = jwtUtil.extractUsername(token); setSecurityContext(username); } }catch (Exception e){ log.error("No valid Token found!", e); } filterChain.doFilter(request, response); } private void setSecurityContext(String username) { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, "", List.of()); SecurityContextHolder.getContext().setAuthentication(authToken); } private String getAuthToken(HttpServletRequest request) { String authHeader = request.getHeader("Authorization"); if(authHeader != null){ return authHeader.replace("Bearer", "").trim(); } return null; } }
AppUserDetailsService implementation
@Service public class AppUserDetailService implements UserDetailsService { private final AppUserRepo appUserRepo; private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); private final JWTUtilService jwtUtilService; public AppUserDetailService(AppUserRepo appUserRepo, JWTUtilService jwtUtilService) { this.appUserRepo = appUserRepo; this.jwtUtilService = jwtUtilService; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return appUserRepo.findByUsername(username) .map(appUser -> User .withUsername(username) .password(appUser.getPassword()) .authorities("user") .build()) .orElseThrow(()-> new UsernameNotFoundException("Username does not exist: "+username)); } public String registerUser(AppUserDTO user) { if(!userExisting(user)){ user.setPassword(encoder.encode(user.getPassword())); appUserRepo.save(user); return jwtUtilService.createToken(new HashMap<>(), user.getUsername()); }else{ throw new UserExistsException("User is currently existing."); } } public boolean userExisting(AppUserDTO user){ return appUserRepo.findByUsername(user.getUsername()).isPresent(); } }
WebSocketMessageBrokerConfigurer implementation
@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/socket").setAllowedOriginPatterns("*"); } }
Here my simplified version of the implementation of the React frontend
Top Level Component
import {StompSessionProvider} from "react-stomp-hooks"; <StompSessionProvider url={"ws://localhost:8080/socket"} topics={['/topic/progress']} onConnect={()=>{console.log("Connected")}} onDisconnect={()=>{console.log("Disconnected")}} onError={(err)=>{console.log(err)}}> <Home/> </StompSessionProvider>
Home Component
import {useSubscription} from "react-stomp-hooks"; export default function ZapContinousHome() { useSubscription("/topic/progress", (message) => setMessage(message.body)); return( <h1>Home</h1> ) }
-
Websocket api at backend using java
Using Java I need to create a websocket connection with UI that just renders data to clients , at Java backend should I use some library or raw socket present in javax package is sufficient? Use case: I have metrics being generated in my application and need to pass the metrics every 2seconds to some UI component using web socket
-
how to create User wise Stomp client connection?
I am working on game engine application. I have following requirement.
I have UserServiceImpl class and one login method in it, once user call login method we are checking username and password .
Now we want apply socket connection in login method. our expectation is when user logged in successfully at that time connection for user should be established and when anyone try to connect using same credential at that we want to give a message like "user is already logged in from another device"
WebSocketClient webSocketClient = new StandardWebSocketClient(); WebSocketStompClient stompClient = new WebSocketStompClient(webSocketClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.setTaskScheduler(new ConcurrentTaskScheduler()); String url = "ws://127.0.0.1:9004/hello"; StompSessionHandler sessionHandler = new MyStompSessionHandler(); stompClient.connect(url, sessionHandler); stompClient.start();
Above code I have written in login method, my question is how to track whether connection is already open for particular user? if credential is different then new connection should be establish and suppose I have more then 1 million users then can I manage this much connection?
-
Rent a new buffer only when I run out of space, not on every read
In the receive loop I'm renting for every read, what I need is to rent a new buffer when I run out of space. How do I do that?
The idea: rent => fill => then grow if needed and replace the buffer
private async Task ReceiveLoopAsync(WebSocket webSocket, CancellationToken cancellationToken) { try { var offset = 0; while (true) { // Rent buffer per message var buffer = ArrayPool<byte>.Shared.Rent(1024); // Memory<byte> overload instead of the ArraySegment one, so we get a ValueTask instead var result = await webSocket.ReceiveAsync(buffer.AsMemory()[offset..], cancellationToken).ConfigureAwait(false); if (result.MessageType == WebSocketMessageType.Close) { break; } if (result.EndOfMessage) { await _incomingMessageQueue.Writer.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); offset = 0; } else { offset += result.Count; // Read buffer size is too small for the message. Doubling... if (offset >= buffer.Length - 1) { // Create the new array var newArray = ArrayPool<byte>.Shared.Rent(buffer.Length * 2); // Copy the old array to the new array Array.Copy(buffer, newArray, offset); //buffer.AsSpan().CopyTo(newArray); // Return the old array ArrayPool<byte>.Shared.Return(buffer); buffer = newArray; } } } } catch (OperationCanceledException) { // normal upon task/token cancellation, disregard } catch (Exception) { // something else happened } finally { _outgoingMessageQueue.Writer.TryComplete(); } }
-
ReceiveAsync's CancellationToken paramtere is doing timeout even if the web socket client is still connected
How do I make
ClientWebSocket.ReceiveAsync
timeout in 5 seconds only if the web socket client is not connected? The current behavior is that it timeouts no matter what conditions are met, i.e. whether the web socket client is connected or not, which is not the behavior I expect.var timeOut = new CancellationTokenSource(5000).Token; var receiveResult = await _clientWebSocket.ReceiveAsync(buffer.Memory, timeOut).ConfigureAwait(false);
-
Best way to mock System.Net.WebSockets ClientWebSocket class to unit test (nunit)
I have used ClientWebSocket class for webSocket communication. What is the best way of mocking the class?