好的一些背景。我正在编写一个从我的世界服务器获取信息的 TCP 客户端。
我想创建一个同时从 10 个服务器获取信息的客户端。所以为此我必须使用多线程。
这是我到目前为止的代码,但它似乎不起作用。
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Module main
Private socketclient As New System.Net.Sockets.TcpClient()
Sub Main()
Dim serverList() As String = _
{"ag1.playeoe.com", "lava-craft.net", "play.diamcraft.com", "mc.ecocitycraft.com", "main.kingscrafters.com", "pvp.cursecraft.net"}
For i = 0 To serverList.Length - 1 Step 1
Console.WriteLine("Connecting to " & serverList(i) & ":" & port & "..")
socketclient.BeginConnect(serverList(i), "25565", New AsyncCallback(AddressOf connect), socketclient)
Threading.Thread.Sleep(1000)
Next
Console.ReadLine()
End Sub
Public Sub connect(ByVal ar As IAsyncResult)
If socketclient.Connected = True Then
Console.WriteLine("Connected!")
Dim stream As NetworkStream = socketclient.GetStream
Dim sendBytes As [Byte]() = {&HFE}
Console.WriteLine("Sending Data...")
stream.Write(sendBytes, 0, sendBytes.Length)
'copied
Console.WriteLine("Recieving Response..." & vbNewLine)
Dim bytes(421) As Byte
stream.Read(bytes, 0, CInt(421))
'Trim Bytes
Dim trimbytes(bytes.Length - 3) As Byte
Array.Copy(bytes, 3, trimbytes, 0, bytes.Length - 3)
'Process output
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("§")
'Display OutPut
Console.WriteLine("----------Response Begin----------")
Console.WriteLine(message(0))
Console.WriteLine(message(1))
Console.WriteLine(message(2))
Console.WriteLine("----------Response End----------" & vbNewLine & vbNewLine)
socketclient.Close()
End If
End Sub
End Module
现在这似乎不起作用。我只从第一台服务器获取数据,而不是其他服务器。当我调试它时,它显示套接字没有为其他服务器打开。
这是输出