【要点】
- 正确导入命名空间
- 使用线程处理业务
- 对异常进行控制,异常是难免的,注意捕捉并正确处理逻辑
【导入命名空间】
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
【初始化变量】
Private ListenerPort As Integer = 888 'TCP监听端口
Private StopFlag As Boolean = False '退出标志
【开始监听】
Dim tcpl As New TcpListener(IPAddress.Any, ListenerPort) '实例TcpListener并绑定到0.0.0.0:888,本例没有检查端口可用性
tcpl.Start()
Do Until StopFlag '循环直到StopFlag=True
'===开始监听===
Dim tcpclt As TcpClient = tcpl.AcceptTcpClient ''定义用于答复的TcpClient
Dim t As New Thread(AddressOf NewConn) '为新TcpClient创建线程
t.Start(Client) '启动线程
Loop
【处理连接】
Private Sub NewConn(Client as TcpClient)
Senddata(Client,Text.Encoding.Utf8.GetBytes("Welcome!")) '发送欢迎信息
Dim Buffer As Byte() = New Byte(4095) {} '定义接收缓冲
Dim RecLength As Integer '定义接收长度
Try
Do Until StopFlag
RecLength = Client.Client.Receive(Buffer)
Select Case RecLength
Case 0
Exit Try '对端断开,跳出流程
Case Else
'正常处理逻辑
Dim Packet as Byte()=new Byte(RecLength-1){}
Array.Copy(Buffer,0,Packet,0,Packet.Length) '获取实际数据
'......
'对实际数据进行处理
'按接收原样答复
SendData(Client,Packet) '逻辑自己调整
End Select
Loop
Catch ex As SocketException
Select Case ex.NativeErrorCode
Case 10053, 10054
'远端断开
Case Else
'其他错误
End Select
End Try
'会话结束
Client.Client.Dispose()
End Sub
【发送答复】
Private Sub SendData(Client as TcpClient,Buffer as byte())
Client.Client.Send(buffer) '发送数据
End Sub