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
上面是我的代码,我基本上想要做的是从文本文件中获取两个(或更多)ips,在两个不同的线程上通过TCP连接到它们,并从服务器获取响应。
现在,问题在于;无论出于何种原因,两个服务器中的一个得到响应但另一个没有。我确保两台服务器都在线并接受连接。我也尝试在文本文件的两行上使用相同的服务器,以便在两个线程上使用相同的ip,但这也不起作用。即使两个ips相同,一个得到响应而另一个得不到;这肯定意味着我做了一些可怕的错误。
当我使用一台服务器而不是1+时,一切都运行良好,我得到了我正在寻找的响应,超过1的任何东西,它看起来像第一个运行的线程产生响应,但没有任何后续运行。任何帮助将不胜感激。
我也尝试过使用Paarallel.For但最终遇到了同样的问题。
Parallel.ForEach(serverlist, _
Sub(currentElement)
ping(currentElement)
End Sub)