.net使用套接字进行通信

时间:2015-12-21 19:50:24

标签: vb.net

我使用此代码通过套接字

发送消息
  Public Shared Function sendMessage(messageBytes As Byte()) As Byte()
        Const bytesize As Integer = 1024 * 1024
        Try
            Dim client As New System.Net.Sockets.TcpClient("127.0.0.1", 8888)
            ' Create a new connection
            Dim stream As NetworkStream = client.GetStream()

            stream.Write(messageBytes, 0, messageBytes.Length)

            messageBytes = New Byte(bytesize - 1) {}

            stream.Read(messageBytes, 0, messageBytes.Length)

            ' Clean up
            stream.Dispose()
            client.Close()
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try

        Return messageBytes
    End Function

这个人应该收到发送的消息,但由于某种原因它不会

服务器代码

 Sub Main()
    Dim client As New TcpClient("127.0.0.1", 8888)
    Dim socket As Socket = client.Client


    Dim buffer As Byte() = New Byte(1024) {}

    Try
        ' Receive data with timeout 10s  
        Receive(socket, buffer, 0, buffer.Length, 10000)
        Dim str As String = Encoding.UTF8.GetString(buffer, 0, buffer.Length)
        MsgBox(str)
    Catch ex As Exception
    End Try
End Sub

调试器说当我尝试运行它时,问题出在第一行 " {"无法建立连接,因为目标计算机主动拒绝了它127.0.0.1:8888"}"

0 个答案:

没有答案