0

程序在加载时冻结。起初它按预期工作,但在我清理并构建解决方案后,它只会在加载时冻结。奇怪的是它只冻结并且不显示捕获的异常消息。

这是我使用的类文件

Imports System.Net ' for IPAddress
Imports System.Net.Sockets 'for TcpListener

Public Class clientSocket
Dim aString As String
Dim port As Integer 'this is the port number
Dim localAddr As IPAddress ' this is the IP address
Dim client As TcpClient ' This is for the TCP/IP Protocol
Dim clientListener As TcpListener

Public Function startSocket() As String
    Try
        'define the two values for your Server
        port = 1234
        localAddr = IPAddress.Loopback 'loopbak = 127.0.0.1 = myself
        clientListener = New TcpListener(localAddr, 4321)
        client = New TcpClient(localAddr.ToString, port)
        Return "Connected to the server"
    Catch ex As Exception
        Return ex.Message
    End Try
End Function

Public Function receive() As String
    Try
        clientListener.Start()
        Dim mySocket As Socket
        mySocket = clientListener.AcceptSocket()
        Dim recieveBuff(225) As Byte
        mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
        Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
        Return str
        mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
        str = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
        clientListener.Stop()
    Catch exp As Exception
        Return "Exception: " + exp.Message
    End Try
End Function
End Class
4

2 回答 2

0
mySocket = clientListener.AcceptSocket()

在接受套接字之前,这些行会阻止进一步的操作,它将阻止您的代码,直到接受套接字为止。使用线程防止阻塞

于 2013-05-12T17:55:20.673 回答
0

或使用BeginAcceptSocket,但您必须将接收代码移至回调。

于 2013-05-12T18:04:11.173 回答