B4J Question Threadsafe map

wl

Well-Known Member
Licensed User
Longtime User
Hi,

In understand that the Server class has a property to create a threadsafe map.

However, I'm also using ServerSockets which, If I'm correct, create a separate thread for each connection as well ?
See the simplified example below (with additional comments)

B4X:
Private Sub server_NewConnection (Successful AsBoolean, NewSocket AsSocket)
  If Successful Then
    streams.Initialize (Me, "streams", NewSocket.InputStream, NewSocket.OutputStream)
    myServer.Listen
  end if
End Sub

Private Sub streams_NewText (text AsString)
  Dim streams AsAsyncStreamsText = Sender
  ...
  'Do all kinds of stuff, but since we can have multiple connections at the same time
  'I would assume we might be entering/executing this method multiple times at the same   time ??
  'So here we could be needing some thread safe Map
End Sub


NewText will be running in a separate thread for each concurrent connection ? Or would calls by different client be serialized ?

I'm still struggling on how multithreading exactly works in B4J. Would one instance of a class be able to have the same method running multiple times in different threads ?

I know it could be better to use the webserver part of B4J but I'm using B4J for all kinds of servers (implemented an SMTP and POP3 server using raw sockets)


UPDATE: if I write an infinite loop in the _NewData event (just for testing), it seems a second connection will never enter the _NewData event. So it seems the server-side process in fact really is NOT multi-threaded, but single threaded and queued ... strange ...

Tx
 
Last edited:

wl

Well-Known Member
Licensed User
Longtime User
Erel,

I see. But as a side effect you get this:

- when a client is flooding the server with messages, the server will not be able to deal with another concurrent connection.
- then I try to build in some security: as soon as a client sends more than X MB's the server closes the connection:
The client messages are still comming through at the server (after the close). I would have guessed that when the server closes a connection the connection indeed is closed, but I guess the closure of the connection will only be executed much later (on the main loop).

How can I protect an external server written in B4J in this case ?
 
Upvote 0
Top