我创建了一个继承TcpClient
类的新类:
Public Class MyTcpClient
Inherits Net.Sockets.TcpClient
Private _ClintName As String
Sub New(ByVal host As String, ByVal port As Integer, ByVal ClientName As String)
MyBase.New(host,port)
_ClintName = ClientName
End Sub
Public Property ClientName()
Get
Return _ClintName
End Get
Set(ByVal value)
_ClintName = value
End Set
End Property
End Class
我尝试连接到TcpListener
的实例:
Try
client = New MyTcpClient(ip, port , "ClientName")
Catch ex As Exception
xUpdate("Can't connect to the server!")
End Try
但是在服务器端,EndAcceptTcpClient
功能存在问题。服务器端代码是这样的:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Dim NewClient As MyTcpClient
Listning = New TcpListener(GetMyIP, 3818)
Listning.Start()
UpdateList("Server Starting", False)
Listning.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listning)
End Sub
Sub AcceptClient(ByVal ar As IAsyncResult)
NewClient = Listning.EndAcceptTcpClient(ar)
UpdateList("New Client Joined!", True)
Listning.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listning)
End Sub
错误发生在AcceptClient
sub的第一行:
NewClient = Listning.EndAcceptTcpClient(ar)
错误消息是:
无法将“System.Net.Sockets.TcpClient”类型的对象强制转换为“ServerChat.MyTcpClient”。
如果我将MyTcpClient
更改为TcpClient
,一切都会好的。
我应该对TcpListener
对象进行任何更改,还是我的尝试错了?