用 vb.net socket通信
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供那坡網(wǎng)站建設(shè)、那坡做網(wǎng)站、那坡網(wǎng)站設(shè)計(jì)、那坡網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、那坡企業(yè)網(wǎng)站模板建站服務(wù),10年那坡做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
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
你這段代碼可以獲得該主機(jī)名下的所有ip,每個(gè)ip地址都是有類型簇的,可以區(qū)別本地地址和網(wǎng)絡(luò)地址、ip6地址。
你獲取索引為0的ip,不一定是正確的網(wǎng)絡(luò)地址,它有時(shí)順序在中間,在后面。
應(yīng)該獲取所有ip,再通過(guò)ip地址簇類型區(qū)分
判斷連接本身有一個(gè)函數(shù),不過(guò)有時(shí)沒(méi)聯(lián)網(wǎng)也是真。
可以用ping,ping百度、ping訪問(wèn)速度快、不經(jīng)常維護(hù)斷線的網(wǎng)絡(luò)主機(jī)。
最簡(jiǎn)單的辦法是用句柄操作窗體,這種方法就好比是計(jì)算機(jī)在代替你在打開(kāi)設(shè)置窗口,完成設(shè)置。
比較難實(shí)現(xiàn)的方法是用API,不過(guò)我不知道用那些API,而且還要驅(qū)動(dòng)支持
因?yàn)関b。net是高級(jí)語(yǔ)言,不能直接操作驅(qū)動(dòng),所以直接寫匯編是不可行的
端口不NAT,兩個(gè)子網(wǎng)中的兩端之間不可能通信。至少要有一方處在公網(wǎng)下或有路由端口映射,不必雙方都映射。
建議題主找本計(jì)算機(jī)網(wǎng)絡(luò)的書研讀一下子網(wǎng)劃分這塊兒。