frmServer.vb 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. Public Class frmServer
  2. 'Public IsClosing As Boolean = False
  3. Private _Server As New tcpCommServer(AddressOf UpdateUI)
  4. Private Function BytesToString(ByVal data() As Byte) As String
  5. Dim enc As New System.Text.UTF8Encoding()
  6. BytesToString = enc.GetString(data)
  7. End Function
  8. Private Function StrToByteArray(ByVal text As String) As Byte()
  9. Dim encoding As New System.Text.UTF8Encoding()
  10. StrToByteArray = encoding.GetBytes(text)
  11. End Function
  12. Public Sub UpdateUI(ByVal bytes() As Byte, ByVal sessionID As Int32, ByVal dataChannel As Integer)
  13. If Me.InvokeRequired() Then
  14. ' InvokeRequired: We're running on the background thread. Invoke the delegate.
  15. Me.Invoke(_Server.ServerCallbackObject, bytes, sessionID, dataChannel)
  16. Else
  17. ' We're on the main UI thread now.
  18. If dataChannel = 1 Then
  19. Me.lbTextInput.Items.Add("Session " & sessionID.ToString & ": " & BytesToString(bytes))
  20. ElseIf dataChannel = 255 Then
  21. Dim tmp = ""
  22. Dim msg As String = BytesToString(bytes)
  23. Dim dontReport As Boolean = False
  24. ' _Server as finished sending the bytes you put into sendBytes()
  25. If msg.Length > 3 Then tmp = msg.Substring(0, 3)
  26. If tmp = "UBS" Then ' User Bytes Sent.
  27. Dim parts() As String = Split(msg, "UBS:")
  28. msg = "Data sent to session: " & parts(1)
  29. End If
  30. If Not dontReport Then Me.ToolStripStatusLabel1.Text = msg
  31. End If
  32. End If
  33. End Sub
  34. Private Sub frmServer_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
  35. _Server.StopRunning()
  36. 'IsClosing = True
  37. End Sub
  38. Private Sub frmServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  39. Me.ToolStripStatusLabel1.Text = "Idle."
  40. frmClient.Show()
  41. End Sub
  42. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btStartServer.Click
  43. If btStartServer.Text = "Start Server" Then
  44. _Server.Start(22490)
  45. btStartServer.Text = "Stop Server"
  46. Else
  47. _Server.StopRunning()
  48. btStartServer.Text = "Start Server"
  49. End If
  50. End Sub
  51. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btSendText.Click
  52. If Me.tbSendText.Text.Trim.Length > 0 Then
  53. _Server.SendBytes(StrToByteArray(Me.tbSendText.Text.Trim))
  54. End If
  55. End Sub
  56. Private Sub btStartNewClient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btStartNewClient.Click
  57. Dim newClient As New frmClient
  58. newClient.Show()
  59. End Sub
  60. End Class