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