I would like to handle the incoming connections in a better way in order to:
- Be noticed when a connection is lost;
- Handle the maximum number of connections;
- Manipulate the array of sockets, stacking the alive connections and cleaning when some connection is lost.
- Prevent the same IP to connect twice at time
- Once a client connects and disconnects afterwards, the sockets(n).connected still returns true
The problem is that I have a limited array size (10 in this case) and every new connection is stacked because I cannot know if whether or not the socket is no longer connected.
Ps.: is the best practice to handle multiple connections by creating arrays for sockets and asyncstreams?
- Be noticed when a connection is lost;
- Handle the maximum number of connections;
- Manipulate the array of sockets, stacking the alive connections and cleaning when some connection is lost.
- Prevent the same IP to connect twice at time
- Once a client connects and disconnects afterwards, the sockets(n).connected still returns true
The problem is that I have a limited array size (10 in this case) and every new connection is stacked because I cannot know if whether or not the socket is no longer connected.
Ps.: is the best practice to handle multiple connections by creating arrays for sockets and asyncstreams?
B4X:
Sub Process_Globals
Dim AStreams(10) As AsyncStreams
Dim Server As ServerSocket
Dim Sockets(10) As Socket
Dim k As Int
End Sub
Sub Globals
Dim EditText1 As EditText
Dim Label1 As Label
End Sub
Sub Activity_Create(FirstTime As Boolean)
Server.Initialize(5500, "Server")
Server.Listen
ToastMessageShow("MyIp = " & Server.GetMyIP, False)
Activity.LoadLayout("1")
End Sub
Sub Server_NewConnection (Successful As Boolean, NewSocket As Socket)
If Successful Then
ToastMessageShow("Connected", False)
Sockets(k) = NewSocket
AStreams(k).Initialize(Sockets(k).InputStream, Sockets(k).OutputStream, "AStreams")
k=k+1
Dim r As Reflector
r.Target = NewSocket
r.Target = r.GetField("socket")
r.Target = r.RunMethod("getInetAddress") 'InetAddress
Dim ip As String = r.RunMethod("getHostAddress")
ToastMessageShow(ip,False)
Else
ToastMessageShow(LastException.Message, True)
End If
Server.Listen
End Sub
Sub AStreams_NewData (Buffer() As Byte)
Dim msg As String
msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
Label1.Text = msg
End Sub
Sub AStreams_Error
ToastMessageShow(LastException.Message, True)
End Sub
Sub EditText1_EnterPressed
For i = 0 To k
Dim buffer() As Byte
buffer = EditText1.Text.GetBytes("UTF8")
AStreams(i).Write(buffer)
Next
End Sub
Sub Activity_Pause(UserClosed As Boolean)
If UserClosed Then
ToastMessageShow("closing", True)
For i = 0 To k
Sockets(i).Close
AStreams(i).Close
Next
Server.Close
Activity.Finish
End If
End Sub
Last edited: