gpt4 book ai didi

vb.net - 多线程和套接字/TCP [VB.NET]

转载 作者:行者123 更新时间:2023-12-03 12:00:55 25 4
gpt4 key购买 nike

我昨天开始学习TCP/Sockets,并决定为我和我的一个 friend 创建一个聊天框。

不幸的是,我在使用多线程时遇到了一些困难。

每当我使用它时,我都不会再收到 friend 的消息。

但是,如果我禁用它,那么一切都将正常运行。

我不知道这是怎么回事,有人可以帮忙吗?

Imports System.Net.Sockets
Imports System.Net

Public Class ServerClient

Dim _TCPServer As Socket
Dim _TCPListener As TcpListener

Dim _ListenerThread As System.Threading.Thread

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click

'When Submit is pressed, send some text to the client

Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(txtInput.Text)
txtBox.AppendText(vbCrLf & "Server: " & txtInput.Text)
txtInput.Clear()
_TCPServer.Send(bytes)

End Sub

Private Sub TCPListen()

'If somebody calls port 2424, accept it, unblock the socket and start the timer

_TCPListener = New TcpListener(IPAddress.Any, 2424)
_TCPListener.Start()
_TCPServer = _TCPListener.AcceptSocket()
btnSend.Enabled = True
txtBox.AppendText("Connection Established" & vbCrLf)
_TCPServer.Blocking = False
_Timer.Enabled = True

End Sub

Private Sub _Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _Timer.Tick

'If data has been sent, receive it

Try

Dim rcvdbytes(_TCPServer.ReceiveBufferSize) As Byte
_TCPServer.Receive(rcvdbytes)
txtBox.AppendText(vbCrLf & "Client: " & System.Text.Encoding.ASCII.GetString(rcvdbytes) & vbCrLf)

Catch ex As Exception
End Try

End Sub

Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Link the new thread to TCPListen(), allow access to all threads and wait for a call

_ListenerThread = New Threading.Thread(AddressOf TCPListen)
Control.CheckForIllegalCrossThreadCalls = False

txtBox.AppendText("Waiting for connection.." & vbCrLf)
btnSend.Enabled = False
_ListenerThread.Start()

End Sub

End Class

最佳答案

此示例项目包含四个类-TcpCommServer,TcpCommClient,clsAsyncUnbuffWriter和CpuMonitor。使用这些类,您不仅可以立即将TCP/IP功能添加到VB.NET应用程序中,而且还拥有我们都在寻找的大多数东西。使用这些类,您将能够将多个客户端连接到同一端口上的服务器。您将能够轻松地:限制客户端的带宽,并通过单个连接同时沿着250个提供的 channel 发送和接收文件和数据(文本?)。

http://www.codeproject.com/Articles/307315/Reusable-multithreaded-tcp-client-and-server-class

关于vb.net - 多线程和套接字/TCP [VB.NET],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16788666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com