代码也很简单:全局代码:
Public server As myServer
Public Class myServer
Private Dim isRunning As Boolean
Public Dim Encoding As Encoding
Private Dim iPort As Integer = 8000
Public Dim thThreadRead As System.Threading.Thread
Public Dim tlTcpListen As System.Net.Sockets.TcpListener
Public Dim tcClient As System.Net.Sockets.TcpClient
Public Sub New(ByVal ip As String, ByVal p As Integer )
Encoding = Encoding.GetEncoding("unicode")
iPort = p
thThreadRead = New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf Listen))
thThreadRead.Start()
End Sub
Private Sub Listen()
Try
tlTcpListen = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, iPort)
tlTcpListen.Start()
tcClient = tlTcpListen.AcceptTcpClient()
MessageBox.Show("已经建立TCP连接!")
Catch ex As System.Security.SecurityException
MessageBox.Show("侦听失败!", "错误")
End Try
End Sub
Public Sub disConnet()
Try
thThreadRead.Abort() ''''中止线程
tlTcpListen.Stop() ''''关闭侦听
tcClient.Close()
MessageBox.Show("停止")
Catch
End Try
isRunning = False
End Sub
End Class
按钮
server = new myserver("127.0.0.1",8000)
If e.sender.Text ="运行" Then
' server.mStart("127.0.0.1",6852)
e.sender.Text ="停止"
Else
'server.disconnet
server.thThreadRead.Abort()
e.sender.Text ="运行"
End If
不知道哪里的问题。