-
用Socket做简单聊天程序(VB.net)
有位网友发贴问我一个聊天的问题,不好拒绝;也看到最近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、客户端
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聊天程序.rar
http://www.cnblogs.com/Files/chendazhi/VB%E8%81%8A%E5%A4%A9%E7%A8%8B%E5%BA%8F.rar
本例只适合初学用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、客户端
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聊天程序.rar
http://www.cnblogs.com/Files/chendazhi/VB%E8%81%8A%E5%A4%A9%E7%A8%8B%E5%BA%8F.rar
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式