Imports System.IO
Imports System.Threading
Imports System.Net.Sockets
Imports System.Text
Module Module1
<MTAThread()>
Sub Main()
Dim maxthreads As Integer = 10
ThreadPool.SetMaxThreads(maxthreads, maxthreads)
Dim serverlist() As String = File.ReadAllLines("final.txt")
Dim servernum As New CountdownEvent(serverlist.GetUpperBound(0) + 1)
For Each a In serverlist
Dim args(1) As Object
args(0) = a
args(1) = servernum
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf ping), args)
Next
servernum.Wait()
Console.ReadLine()
End Sub
Public Sub ping(ByVal server() As Object)
Dim serverinfo() As String = Split(server(0), ",")
Dim socketclient As New TcpClient
Console.WriteLine(serverinfo(0))
Try
socketclient.Connect(serverinfo(0), serverinfo(1))
Catch ex As Exception
If socketclient.Connected = False Then
Throw New Exception("Server Offline")
Else
Throw New Exception("Unknown Error Occured")
End If
End Try
Dim stream As NetworkStream = socketclient.GetStream
stream.ReadTimeout = 1000
stream.WriteTimeout = 1000
Dim sendBytes As [Byte]() = {&HFE}
stream.Write(sendBytes, 0, sendBytes.Length)
Dim bytes(421) As Byte
stream.Read(bytes, 0, CInt(421))
socketclient.Close()
Dim trimbytes(bytes.Length - 3) As Byte
Array.Copy(bytes, 3, trimbytes, 0, bytes.Length - 3)
Dim returndata As String = Encoding.BigEndianUnicode.GetString(trimbytes)
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To 241 Step 2
If trimbytes(i) <> 0 Then
sb.Append(ChrW(BitConverter.ToInt16(trimbytes, i)))
End If
Next i
Dim message() As String = sb.ToString.Split("§")
'Write processed server information to the console
Console.WriteLine("Received -->" & message(1) & " " & message(2) & " | " & serverinfo(0))
server(1).signal()
End Sub
End Module
以上是我的代码,我基本上想做的是从文本文件中获取两个(或更多)ip,通过两个不同线程上的 TCP 连接到它们并从服务器获取响应。
现在,这里的问题是;无论出于何种原因,两台服务器中的一台得到响应,而另一台没有。我已确保两台服务器都在线并接受连接。我还尝试在文本文件的两行上使用相同的服务器,以便在两个线程上使用相同的 ip,但这也不起作用。即使两个 ip 相同,一个得到响应但另一个没有;这一定意味着我做错了什么。
当我使用一个服务器而不是 1+ 时,一切正常,我得到了我正在寻找的响应,任何超过 1 的东西,看起来像第一个运行的线程会产生响应,但不会产生任何稍后运行的东西。任何帮助将不胜感激。
我也尝试过使用 Paarallel.For 但最终遇到了同样的问题。
Parallel.ForEach(serverlist, _
Sub(currentElement)
ping(currentElement)
End Sub)