用Socket做簡單聊天程式(VB.net)
阿新 • • 發佈:2021-02-11
有位網友發貼問我一個聊天的問題,不好拒絕;也看到最近VB.net版問這個的人很多,就寫了一個放在這裡。
本例只適合初學用Socket程式設計的人,因而力求簡單,讓老鳥見笑了J
另本示例用的是vs2005
1、服務端
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
'傳送資訊
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim msg As Byte() = Encoding.UTF8.GetBytes("Chat|" + TextBox1.Text)
mySocket.Send(msg)
ListBox1.Items.Add("本地資訊: " + TextBox1.Text)
TextBox1.Text = ""
End Sub
'非UI執行緒呼叫窗體控制元件,保證執行緒安全。與聊天實現無關。
Sub AddInfo(ByVal sender As System.Object, ByVal e As System.EventArgs)
ListBox1.Items.Add("遠端資訊: " + sender.ToString)
End Sub
'關閉視窗時發關退出資訊並清理資源
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If IsRun Then
Dim msg As Byte() = Encoding.UTF8.GetBytes("Exit|服務端退出: " + Me.Handle.ToString)
Dim bytesSent As Integer = mySocket.Send(msg)
End If
listener.Close()
mySocket = Nothing
myThread.Abort()
End Sub
End Class
2、客戶vb.net教程端
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class frmClient
'客戶端Socket
Dim cliSocket As Socket
'連線狀態
Dim IsConnected As Boolean = False
'接收資訊執行緒
Dim myThread As Thread
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim remoteEP As New IPEndPoint(Net.IPAddress.Parse("127.0.0.1"), 11000)
cliSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Try
cliSocket.Connect(remoteEP)
ListBox1.Items.Add("連線服務端成功!")
IsConnected = True
myThread = New Thread(AddressOf ReciveMsg)
myThread.Start()
Catch ex As Exception
ListBox1.Items.Add(ex.Message)
End Try
End Sub
Sub ReciveMsg()
Dim bytes() As Byte = New Byte(1024) {}
Dim data As String = String.Empty
Dim tokens() As String
While True
Dim bytesRec As Integer = cliSocket.Receive(bytes)
data = Encoding.UTF8.GetString(bytes, 0, bytesRec)
tokens = data.Trim.Split("|")
Select Case tokens(0) '分析接收到的資料,可自己定義更多一些
Case "Exit"
IsConnected = False
BeginInvoke(New EventHandler(AddressOf AddInfo), tokens(1)) 'Invoke保證執行緒安全
cliSocket.Shutdown(SocketShutdown.Both)
cliSocket.Close()
Exit Sub
Case "Chat"
BeginInvoke(New EventHandler(AddressOf AddInfo), tokens(1)) 'Invoke保證執行緒安全
End Select
End While
End Sub
'傳送資訊
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim msg As Byte() = Encoding.UTF8.GetBytes("Chat|" + TextBox1.Text)
Dim bytesSent As Integer = cliSocket.Send(msg)
ListBox1.Items.Add("本地資訊: " + TextBox1.Text)
TextBox1.Text = ""
End Sub
'非UI執行緒呼叫窗體控制元件,保證執行緒安全。與聊天實現無關。
Sub AddInfo(ByVal sender As System.Object, ByVal e As System.EventArgs)
ListBox1.Items.Add("遠端資訊: " + sender.ToString)
End Sub
'關閉視窗時發關退出資訊並清理資源
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If IsConnected Then
Dim msg As Byte() = Encoding.UTF8.GetBytes("Exit|客戶端退出: " + Me.Handle.ToString)
Dim bytesSent As Integer = cliSocket.Send(msg)
myThread.Abort()
End If
End Sub
End Class
源程式下載:
VB聊天程式.rarhttp://www.cnblogs.com/Files/chendazhi/VB%E8%81%8A%E5%A4%A9%E7%A8%8B%E5%BA%8F.rar