【C#】用VncSharp库来实现自建VNC Server服务器,连接时需要提供密码
				
									
					
					
						|  | 
							admin 2025年2月25日 12:48
								本文热度 2132 | 
					
				 
				以下是使用 VncSharp 库实现带有密码验证的 VNC 服务端的完整代码示例:
步骤 1:安装 NuGet 包
Install-Package VncSharp -Version 1.0.0
步骤 2:完整服务端代码
using System;
using System.Drawing;
using VncSharp;
public class SecureVncServer : VncServer
{
    // 设置 VNC 连接密码(需为 8 字符)
    private readonly string vncPassword = "12345678";
    public SecureVncServer()
    {
        // 设置密码(自动转换为 VNC 认证格式)
        Password = vncPassword.ToCharArray();
    }
    protected override void ProvidePassword(byte[] challenge)
    {
        // 密码验证逻辑(VncSharp 自动处理加密验证)
    }
    // 屏幕捕获实现
    public override Bitmap CaptureScreen()
    {
        Rectangle bounds = Screen.PrimaryScreen.Bounds;
        Bitmap bmp = new Bitmap(bounds.Width, bounds.Height);
        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
        }
        return bmp;
    }
}
class Program
{
    static void Main()
    {
        var vncServer = new SecureVncServer();
        
        // 启动服务(端口 5900)
        try 
        {
            vncServer.Start(5900);
            Console.WriteLine($"VNC Server 已启动,密码: {vncServer.Password}");
            Console.WriteLine("按 Enter 键停止服务...");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"启动失败: {ex.Message}");
        }
        finally
        {
            vncServer.Stop();
        }
    }
}
关键配置说明
- 密码规则: 
- 必须为 8 个 ASCII 字符 
- 示例密码 12345678 可替换为自定义密码 
- 实际传输使用 DES 加密(VNC 标准) 
- 端口配置: 
vncServer.Start(5900); // 标准 VNC 端口
- 可通过防火墙开放对应端口 
- 屏幕捕获优化: 
// 可添加帧率控制(例如每秒 30 帧)
Timer updateTimer = new Timer
{
    Interval = 1000 / 30,
    Enabled = true
};
updateTimer.Tick += (s, e) => RefreshScreen();
客户端连接验证
- 使用 TightVNC/RealVNC 客户端 
- 地址输入 IP:5900 
- 输入预设密码连接 
增强安全建议
// 在 SecureVncServer 类中添加:
protected override void RegisterMessages()
{
    base.RegisterMessages();
    // 禁用不安全的安全类型
    SecurityTypes = new[] { SecurityType.VncAuthentication };
}
// 添加连接审计
public override void RegisterClient(VncClientProxy client)
{
    Console.WriteLine($"[{DateTime.Now}] 新连接来自 {client.RemoteAddress}");
    base.RegisterClient(client);
}
协议兼容性配置
如需支持更多客户端,可修改初始化:
public SecureVncServer()
{
    // 设置 RFB 协议版本
    RfbVersion = "3.8";
    // 支持的编码格式
    SupportedEncodings = new[] { 
        EncodingType.Raw, 
        EncodingType.Hextile 
    };
}
此实现完整包含密码验证机制,建议在实际部署时:
- 使用更复杂的密码策略 
- 添加 TLS 加密(需额外实现) 
- 记录连接日志 
该文章在 2025/2/25 12:58:17 编辑过