用 vb.net socket通信
遂川網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、APP開(kāi)發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)等網(wǎng)站項(xiàng)目制作,到程序開(kāi)發(fā),運(yùn)營(yíng)維護(hù)。成都創(chuàng)新互聯(lián)從2013年成立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來(lái)保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。
Dim th As Threading.Thread
2 Dim tcpl As System.Net.Sockets.TcpListener
3
4 Private Sub Form1_Load()Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
5 th = New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf MyListen))
6 th.Start()
7 End Sub
8
9 Public Sub SendMessage()Sub SendMessage(ByVal IP As String, ByVal SendMsg As String)
10 Try
11 If IP "" Then
12 Dim tcpc As New System.Net.Sockets.TcpClient(IP, 5656)
13 Dim tcpStream As Net.Sockets.NetworkStream = tcpc.GetStream
14 Dim reqStream As New IO.StreamWriter(tcpStream)
15 reqStream.Write(SendMsg)
16 reqStream.Flush()
17 tcpStream.Close()
18 tcpc.Close()
19 End If
20 Catch ex As Exception
21 MsgBox(ex.Message.ToString)
22 End Try
23 End Sub
24 Private Sub MyListen()Sub MyListen()
25 Try
26 Dim ipAddress As System.Net.IPAddress = System.Net.Dns.Resolve(System.Net.Dns.GetHostName).AddressList(0)
27 tcpl = New System.Net.Sockets.TcpListener(ipAddress, 5656)
28 tcpl.Start()
29 While True
30 Dim s As System.Net.Sockets.Socket = tcpl.AcceptSocket()
31 Dim MyBuffer(1024) As Byte
32 Dim i As Integer
33 i = s.Receive(MyBuffer)
34 If i 0 Then
35 Dim lstrRec As String
36 Dim j As Integer
37 For j = 0 To i - 1
38 TextBox1.Text += Chr(MyBuffer(j)) ","
39 Next
40 End If
41 End While
42 Catch ex As Exception
43 MsgBox(ex.Message.ToString)
44 End Try
45 End Sub
46
47 Private Sub Button1_Click()Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
48 SendMessage("192.168.0.61", TextBox2.Text)
49 End Sub
最簡(jiǎn)單的就是定義靜態(tài)變量,然后在各個(gè)線程之間通過(guò)lock來(lái)訪問(wèn)或修改變量
試試這個(gè)怎么樣,添加在子進(jìn)程里面,就加在你批量傳輸代碼里的每一個(gè)傳輸后面,也就是大批量中的每傳輸一個(gè)數(shù)據(jù)就暫停一下,而不是每一個(gè)大批量才暫停一下
System.Threading.Thread.Sleep(10) '讓它走慢一點(diǎn)
關(guān)于串口通訊的問(wèn)題:
很明顯,你還不知道(不會(huì)、不習(xí)慣)使用事件驅(qū)動(dòng)的方式接收數(shù)據(jù)。
建議你仔細(xì)看看串口組件(無(wú)論VB6還是VB.net)的OnComm事件,你的問(wèn)題很容易解決。
關(guān)于以太網(wǎng)通訊:
在TCP通訊中端口確實(shí)可以重用,你百度一下“TCP端口重用”能查到很多示例。
但絕大多數(shù)情況下不推薦端口重用,而應(yīng)該采取服務(wù)器端建立連接池的方法。
或者,干脆不用TCP,用UDP解決也可以。