Using streams through TcpClient and TcpServer

2019-09-14 02:50发布

I try to send data from server (TcpListener) to client (TcpClient). I use Windows Form Application and the next code:

Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Runtime.InteropServices

Public Class Form1

Private Server As TcpListener = Nothing
Private ServerThread As Thread = Nothing
Dim tcpclnt As TcpClient
Dim stream As NetworkStream

Public Shared bytes(1024) As Byte
Public Shared data As String = Nothing


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown
    Server = New TcpListener(IPAddress.Any, 40000)
    ServerThread = New Thread(AddressOf ConnectionListener)
    ServerThread.IsBackground = True
    ServerThread.Start()
    TextBox1.Text = "Server started!"

End Sub

Private Sub ConnectionListener()
    Try
        Server.Start()


        While True
            Dim myClient As TcpClient = Server.AcceptTcpClient()
            Dim T As New Thread(AddressOf SomeClientActions)
            T.Start(myClient)
            Invoke(Sub() TextBox1.Text = TextBox1.Text + Environment.NewLine + "Client connected")


            ' HERE IM TRYING TO READ DATA FROM STREAM
            stream = myClient.GetStream()
            Dim i As Int32
            i = stream.Read(bytes, 0, bytes.Length)

            While True
                ' Translate data bytes to a ASCII string.
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
                Invoke(Sub() TextBox3.Text = "Received: {0}" + data)

                ' Process the data sent by the client.
                data = data.ToUpper()
                Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)

                ' Send back a response.
                stream.Write(msg, 0, msg.Length)
                Invoke(Sub() TextBox3.Text = "Sent: {0}" + data)

                i = stream.Read(bytes, 0, bytes.Length)

           End While


            myClient.Close()
        End While

    Catch ex As Exception
        MessageBox.Show("Unable to Accept Connections", "Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End Try
    Application.ExitThread()

End Sub

Private Sub SomeClientActions(ByVal client As Object)
    ' ... do something with "client" in here ...
    ' MAYBE SOME CODE HERE?..
End Sub


Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    Server.Stop()
End Sub


Private Sub ButtonClientConnection_Click(sender As Object, e As EventArgs) Handles Button2.Click
    tcpclnt = New TcpClient()
    tcpclnt.Connect("127.0.0.115", 40000)
End Sub

Private Sub ButtonSendData_Click(sender As Object, e As EventArgs) Handles Button3.Click
    ' HERE IM TRYING TO WRITE DATA TO STREAM FROM TEXTBOX
    Dim msg As New System.IO.StringReader(TextBox2.Text)
    Dim msgstr As String = msg.ReadToEnd
    Dim msgbyte() As Byte = Encoding.UTF8.GetBytes(msgstr)
    stream.Write(msgbyte, 0, msgbyte.Length)
End Sub


End Class

What I'm trying to do: I create server, then press button ButtonClientConnection' and create and connect client (TcpClient). That works - I get stringsServer startedandClient connected` in textbox1.

Now I want to do: put some text in textbox2, press button ButtonSendData and transmit this data from client to server through the stream and write this data to another textbox (textbox3). My attempts are here in the code, but nothing is happens - As I see in debugger I write some data in stream, but can't read it because my code for reading data from stream executes only 1 time at client connection.

How to read data permanently? And write it correctly to stream by pressing ButtonSendData? I made some workaround and it looks like it stuck at line:

i = stream.Read(bytes, 0, bytes.Length)

Code stops here and can't go further in this thread.

1条回答
劳资没心,怎么记你
2楼-- · 2019-09-14 03:35

You're sending data through the wrong stream. stream is the server's stream, but you have no stream for tcpclnt.

Try this:

Dim clientstream As NetworkStream

Private Sub ButtonClientConnection_Click(sender As Object, e As EventArgs) Handles Button2.Click
    tcpclnt = New TcpClient()
    tcpclnt.Connect("127.0.0.115", 40000)
    clientstream = tcpclnt.GetStream()
End Sub

Private Sub ButtonSendData_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim msgbyte() As Byte = Encoding.UTF8.GetBytes(TextBox2.Text)
    clientstream.Write(msgbyte, 0, msgbyte.Length)
End Sub

As you see I have also removed the StringReader because it was completely unnecessary. You were creating it only to read it back to a string again, where you can just get the bytes from TextBox2.Text directly instead.

查看更多
登录 后发表回答