作者Xavier (X.avi(er))
看板Visual_Basic
標題[.NET] Textbox 內容消失
時間Mon Apr 25 17:05:35 2016
大家好!
我寫一個 SERVER SOCKET接收資料,
Dim ListenThread As New Thread(AddressOf StartListen)
ListenThread.IsBackground = True
ListenThread.Start()
////////////////////////////////////////////////////
Private Sub StartListen()
Try
serverSocket = New Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)
Dim serverIP As IPAddress = IPAddress.Parse(txtip.Text)
Dim Port As String = txtport.Text
Dim serverhost As New IPEndPoint(serverIP, Int32.Parse(Port))
serverSocket.Bind(serverhost)
serverSocket.Listen(50)
UpdateText("Server started at: " + serverIP.ToString() + ":" +
Port)
Do
ClientSocket = serverSocket.Accept()
If ClientSocket.Connected = True Then
Dim ReceiveThread As New Thread(AddressOf ReceiveData)
ReceiveThread.IsBackground = True
ReceiveThread.Start()
End If
Loop
Catch ex As Exception
UpdateText(ex.StackTrace.ToString())
End Try
////////////////////////////////////////////////////////
Private Sub ReceiveData()
Dim myNetworkStream As New NetworkStream(ClientSocket)
Dim InBytesCount As Integer = 0
Dim myReceiveBytes(1023) As Byte
Dim i As Integer = 0
While True
Try
InBytesCount = myNetworkStream.Read(myReceiveBytes, 0,
myReceiveBytes.Length)
System.Threading.Thread.Sleep(100)
If InBytesCount = 0 Then
Exit While
End If
UpdateText(Encoding.GetEncoding(950).GetString(myReceiveBytes).
TrimEnd().TrimStart())
Catch ex As Exception
MessageBox.Show(ex.ToString)
Exit Sub
End Try
End While
End Sub
//////////////////////////////////////////////////////////////
Private Sub UpdateText(ByVal comData As String)
'如果呼叫txtReceive的是另外的執行緒,傳回True
If Me.TxtReceive.InvokeRequired Then
'利用委派型別建立委派物件,並指定委派的函式
Dim d As New SetTextCallback(AddressOf GetUpdateText)
'用大括號 {} 括住初始值,藉以初始化陣列的值。
Try
Me.Invoke(d, New Object() {comData})
'以指定的引數清單叫用函式
Catch ex As Exception
End Try
Else '相同的執行緒
GetUpdateText(comData) '將收到的資料填入接收文字框中
End If
End Sub
///////////////////////////////////////////////////////////////
Private Sub GetUpdateText(ByVal comData As String)
txtRecord.Text = comData + vbCrLf + txtRecord.Text
End Sub
然後我用手機當CLIENT發送幾道指令,EX. (STX)123456(ETX)
結果 txtRecord 只會顯示當下收到的指令,
而沒有印出所有指令,
請問要怎麼修改才能印出所有指令呢?
感謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.221.47.106
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Visual_Basic/M.1461575137.A.08C.html
1F:推 Marty: Textbox屬性改成可以顯示多行? 04/25 17:12
2F:→ Xavier: 已經是多行了! 3Q 04/25 17:14
3F:→ Xavier: StartListen()裡面也會印資料,也會疊加舊內容 04/25 17:16
4F:→ Xavier: 唯獨 ReceiveData()裡印資料之後卻只剩最新的一行 04/25 17:17
5F:→ Xavier: 不知道是為什麼...orz 04/25 17:25
6F:→ niwat: 加入application.doevent會不會有用? 04/26 09:36