Imports System.Net.Sockets
Imports System.Net
Imports System.Threading
Public Class Form1
Dim bin_buf(1024) As Byte
Dim id_socket As New Hashtable
Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim localEndPoint As IPEndPoint
Dim send_socket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
bin_buf(0) = 1
bin_buf(1) = 2
bin_buf(2) = 3
Dim t As New Thread(AddressOf accept_link)
t.Start()
End Sub
Private Sub accept_link()
localEndPoint = New IPEndPoint(IPAddress.Parse("127.0.0.1"), Val(TextBox1.Text)) ' '''指定IP和Port
Try
s.Bind(localEndPoint) ' '''绑定到该Socket
Catch
'提示端口被占用
MsgBox("端口被占用")
End
End Try
s.Listen(100) ''''侦听,最多接受100个连接
Do
Dim new_s As Socket = s.Accept()
Dim t As New Thread(AddressOf process_sub)
t.Start(new_s)
Loop
End Sub
Private Sub process_sub(ByVal s As Socket)
Dim buf(1023) As Byte
Dim sbuf(1) As Byte
Dim l As Long
Do
l = s.Receive(buf)
If l > 0 Then
If l = 1 Then
If id_socket.ContainsKey(buf(0).ToString) = False Then
id_socket.Add(buf(0).ToString, s)
End If
send_socket = s
End If
Else
s.Close()
Exit Do
End If
Loop
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim s As String = ""
For Each i As DictionaryEntry In id_socket
s &= "ID:" & i.Key & " socket:" & i.Value.ToString & vbCrLf
Next
TextBox2.Text = s
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim s As String
s = TextBox3.Text
If id_socket.ContainsKey(s) = True Then
Dim ss As Socket
Dim buf(0 To 6)
buf(0) = &H68
buf(1) = &H65
buf(2) = &H6C
buf(3) = &H6C
buf(4) = &H6F
buf(5) = &HD
buf(6) = &HA
ss = CObj(id_socket.Item(s))
ss.Send(buf)
End If
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim buf(0 To 6)
buf(0) = &H68
buf(1) = &H65
buf(2) = &H6C
buf(3) = &H6C
buf(4) = &H6F
buf(5) = &HD
buf(6) = &HA
send_socket.Send(buf)
End Sub
End Class
运行到ss.endf(buf)报错:
System.InvalidCastException:“无法将类型为“System.Object[]”的对象强制转换为类型“System.Collections.Generic.IList1[System.ArraySegment
1[System.Byte]]”。”
是Hashtable无法保存socket对象,还是程序哪写的不对。还请懂的赐教