通过 TcpClient 和 TcpServer 使用流 [英] Using streams through TcpClient and TcpServer

查看:33
本文介绍了通过 TcpClient 和 TcpServer 使用流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将数据从服务器 (TcpListener) 发送到客户端 (TcpClient).我使用 Windows 窗体应用程序和下一个代码:

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

我想要做的是:我创建服务器,然后按下按钮 ButtonClientConnection' 并创建并连接客户端 (TcpClient).这有效 - 我在 textbox1 中得到字符串服务器启动客户端连接`.

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.

现在我想做:在 textbox2 中放入一些文本,按下按钮 ButtonSendData 并通过流将此数据从客户端传输到服务器,并将此数据写入另一个文本框 (textbox3).我的尝试在代码中,但没有任何反应 - 正如我在调试器中看到的,我在流中写入了一些数据,但无法读取它,因为我从流中读取数据的代码仅在客户端连接时执行 1 次.

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.

如何永久读取数据?并按 ButtonSendData 正确写入流?我做了一些解决方法,看起来它卡在了线上:

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.

推荐答案

您通过错误的流发送数据.stream 是服务器的流,但您没有 tcpclnt 的流.

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

试试这个:

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

如您所见,我还删除了 StringReader,因为它完全没有必要.您创建它只是为了再次将其读回字符串,您可以直接从 TextBox2.Text 获取字节.

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.

这篇关于通过 TcpClient 和 TcpServer 使用流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆