Tcp客户端/服务器 - 客户端消息问题

时间:2014-11-05 09:01:00

标签: vb.net tcp

我有客户端和服务器应用程序。

我让客户端通过断开连接按钮与client.close断开连接。

我发送一条消息,在服务器上显示。好的很棒。

我断开然后重新连接。我发了一条消息。它会两次显示该消息。

我断开了另一次,然后重新连接。我发了一条消息。然后它会三次显示该消息。

它正在递增消息并在断开连接后多次发送,然后重新连接。

帮助?一直试图解决这个问题

[SERVER]

Public Class Server
Dim Listener As TcpListener
Dim Client As TcpClient
Dim ListenerThread As System.Threading.Thread
Dim ClientID As String
Dim ClientIP As String
Dim ClientIPandID As String
Dim ClientIPandPort As String
Dim TotalItemCount As String
Dim clientcount As Integer = 0

Private Sub Server_Load(sender As Object, e As EventArgs) Handles Me.Load
    CheckForIllegalCrossThreadCalls = False

End Sub

Private Sub ButtonStart_Click(sender As System.Object, e As System.EventArgs) Handles ButtonStart.Click
    If TextBoxPort.Text = "" Then
        MsgBox("Please Enter Port To Run On.")
    Else

        ListenerThread = New System.Threading.Thread(AddressOf Listening)
        ListenerThread.IsBackground = True
        ListenerThread.Start(TextBoxPort.Text)
        ButtonStart.Enabled = False
        ButtonStop.Enabled = True
        ListBox1.Items.Add("[SERVER] Running on Port " + TextBoxPort.Text)
        ListBox1.Items.Add("[SERVER] Waiting For A Connection...")
    End If

End Sub

Private Sub Listening(ByVal Port As Integer)

    Try
        Listener = New TcpListener(IPAddress.Any, Port)
        Listener.Start()
        Do
            Client = Listener.AcceptTcpClient 'Accepts Client Trying To Connect
            If Client.Connected Then
                MsgBox("Client Connected")
            End If
            clientcount += 1
            GetClientInfo() 'Retrieves The Clients Info
            AddHandler ReceivedMessage, AddressOf ReceivedMessage1
        Loop Until False
    Catch ex As Exception
    End Try
End Sub
'Events
Public Event ReceivedMessage(ByVal Command As String)

Private Sub GenerateClientSessionNumber()
    Dim r As New Random
    Dim x As String = String.Empty
    For i = 0 To 7
        x &= Chr(r.Next(65, 89))
    Next
    ClientID = x
End Sub

Private Sub GetClientInfo()
    GenerateClientSessionNumber()
    ClientIPandID = Client.Client.RemoteEndPoint.ToString().Remove(Client.Client.RemoteEndPoint.ToString().LastIndexOf(":")) & " - " & ClientID
    ClientIP = Client.Client.RemoteEndPoint.ToString().Remove(Client.Client.RemoteEndPoint.ToString().LastIndexOf(":"))
    ClientIPandPort = Client.Client.RemoteEndPoint.ToString()
    MsgBox(ClientIPandPort)
    ListBox2.Items.Add(ClientIPandID)
    Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
End Sub

Private Sub ButtonStop_Click(sender As System.Object, e As System.EventArgs) Handles ButtonStop.Click
    Listener.Stop()
    Client.Close()
    ButtonStop.Enabled = False
    ButtonStart.Enabled = True
    ListBox1.Items.Add("[SERVER] Server Stopped")
End Sub


Private Sub Reading()
    Try
        Dim Reader As New StreamReader(Client.GetStream)

        Dim Command As String = Reader.ReadLine

        Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
            RaiseEvent ReceivedMessage(command)
    Catch ex As Exception
    End Try
End Sub



Private Sub ReceivedMessage1(ByVal Command As String)
    Dim Message() As String = Command.Split("|")
    If Message(0) = "MESSAGE" Then
        MsgBox("Message Received From Client " + ">" + Message(1))
    End If
end sub

[CLIENT]

Public Class Client
Dim Client As New TcpClient
Sub Connect(ByVal ServerIP As String, ByVal Port As Integer)
    'Try To Make Connection With Server
    If Client.Connected = True Then
        MsgBox("Already Connected")
        MsgBox("Connected To " + Client.Client.RemoteEndPoint.ToString)
    Else
        MsgBox("Currently Not Connected. Trying To Connect...")
        Try
            Client.Connect(ServerIP, Port)
            MsgBox("Connected")
            Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
        Catch ex As Exception
            MsgBox("Could Not Connect To Server. Check Server." + ex.Message.ToString)
        End Try
    End If
End Sub


Private Sub SendData(ByVal Message As String) 'Sends Data to Server
    TextBox1.Text = Message
    Try
        If Client.Connected = True Then
            Dim Writer As New StreamWriter(Client.GetStream)
            Writer.WriteLine(Message)
            Writer.Flush()
        Else
            MsgBox("Cannot Send Message. Connection To Server Is Not Active.")
        End If
    Catch ex As Exception
        MsgBox("You Are Not Connected To The Server." + vbCrLf + ex.Message.ToString)
    End Try
End Sub


Private Sub ButtonConnect_Click(sender As Object, e As EventArgs) Handles ButtonConnect.Click
    Connect(TextBoxIPAddress.Text, TextBoxPort.Text)
End Sub

Private Sub ButtonSendMessage_Click(sender As Object, e As EventArgs) Handles ButtonSendMessage.Click
    SendData("MESSAGE|" & TextBoxMessage.Text)
End Sub

Private Sub Client_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    CheckForIllegalCrossThreadCalls = False
End Sub    


Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
    SendData("DISCONNECT|")
    Client.Close()
    Client = New TcpClient
End Sub

End Class

2 个答案:

答案 0 :(得分:-1)

我不确定这个问题但是我可以给你一些假设,首先你在客户端上添加处理程序你连接在服务器一侧,这意味着多个指针指向在同一个地方,其次,当您连接到服务器并且重新连接时,您实际上并没有告诉服务器这两个客户端是相同的,所以他做了两个客户端和服务器之间的渠道,第一个是旧的 没有关闭,并且他仍然有处理程序,服务器don&认识到第一个是断开连接,因为他已经连接了!即使它是客户端的另一个对象。因此,当客户断开连接断开他与服务器,或每次循环测试客户端是否已连接,然后再接受做这个测试。

答案 1 :(得分:-1)

因为我有一个叫Called" ConnectedClient"的课程。我能够调用该特定客户端或所有客户端并关闭/销毁连接。