永发信息网

vb.net socket 编程问题(帮我把粗体字部分解释一下)

答案:1  悬赏:60  手机版
解决时间 2021-05-16 01:05
  • 提问者网友:椧運幽默
  • 2021-05-15 18:45

Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Diagnostics

Public Class frmServer

'服务端的Socket
Dim listener As Socket
'与客户端会话的Socket
Dim mySocket As Socket
'服务端的运行状态
Dim IsRun As Boolean = False
'监听接收数据线程
Dim myThread As Thread

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
myThread = New Thread(AddressOf Listen)
myThread.Start()
End Sub

Public Sub Listen()
Dim bytes() As Byte = New [Byte](1024) {}
Dim data As String = String.Empty
Dim tokens() As String

Dim localEndPoint As New
IPEndPoint(Net.IPAddress.Parse("127.0.0.1"), 11000)
'初始化socket
listener = New Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)
'绑定端口
listener.Bind(localEndPoint)
'开始监听
listener.Listen(10)

BeginInvoke(New EventHandler(AddressOf AddInfo),
"服务端已启动,正在等待连接......")

mySocket = listener.Accept()
IsRun = True

While True
Dim bytesRec As Integer = mySocket.Receive(bytes)
data = Encoding.UTF8.GetString(bytes, 0, bytesRec)

tokens = data.Trim.Split("|")
Select Case tokens(0) '分析接收到的数据,可自己定义更多一些
Case "Chat"
BeginInvoke(New EventHandler(AddressOf AddInfo),
tokens(1)) 'Invoke保证线程安全
Case "Exit"
IsRun = False
BeginInvoke(New EventHandler(AddressOf AddInfo),
tokens(1)) 'Invoke保证线程安全
mySocket.Shutdown(SocketShutdown.Both)
mySocket.Close()
Exit Sub
End Select
End While

End Sub

最佳答案
  • 五星知识达人网友:荒野風
  • 2021-05-15 20:00

mySocket = listener.Accept() '响应联结请求,并且新建一个套接口。原来的套接口则返回监听状态。

Dim bytesRec As Integer = mySocket.Receive(bytes) '接收数据到bytes数组
data = Encoding.UTF8.GetString(bytes, 0, bytesRec) '将接收到的数据用UTF8编码转为字串


tokens = data.Trim.Split("|") '以 "|" 格式化字串(拆分)

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯