c# 实现远程控制

发布时间:2009年07月31日      浏览次数:871 次
首先  我们得明白我们需要做些什么这里我们把运行在我们自己电脑上的控制程序叫 Server  被管理电脑运行的程序叫Client(1)既然是远程控制  那么 得让你和被管理的计算机之间有连接 (2)有了连接 我们就在我们的Server端发送命令来做我们想要做的事(3)Client端接收到我们在Server端发送的命令后,在被管理电脑上进行操作,将结果返回给Server端那么,我们就来一步一步的来实现打开studio2005新建一个控制台程序取名 Server以下是Server端程序using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;namespace Server
{
class Program
{
static void Main(string[] args)
{
IPAddress ipAd = IPAddress.Parse("10.3.128.240"); // 把IP地址转换为IPAddress的实例
// 初始化监听器, 端口为8888
TcpListener myList = new TcpListener(ipAd, 8888);
// 开始监听服务器端口
myList.Start();
// 输出服务器启动信息
Console.WriteLine("在8888端口启动服务...");
Console.WriteLine("本地节点为:" + myList.LocalEndpoint);
Console.WriteLine("等待连接.....");// 等待处理接入连接请求
// 新建立的连接用套接字s表示
Socket s = myList.AcceptSocket();
Console.WriteLine("连接来自 " + s.RemoteEndPoint);
//发送命令
while(s.Connected)
{
ASCIIEncoding asen = new ASCIIEncoding();
Console.WriteLine("请输入指令:\n");
s.Send(asen.GetBytes(Console.ReadLine()));
//接收返回信息
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
{Console.Write(Convert.ToChar(b[i]));
}
Console.WriteLine("\n已发送命令");
}
}
}
}以下是Client端程序using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;namespace Client
{
class Program
{
static void Main(string[] args)
{
// 新建客户端套接字
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("连接.....");// 连接服务器
tcpclnt.Connect("10.3.128.240", 8888);
Console.WriteLine("已连接");
// 得到客户端的流
Stream stm = tcpclnt.GetStream();
// 接收从服务器返回的信息
while (tcpclnt.Connected)
{
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string a = null;
for (int i = 0; i < k; i++)
{
a += Convert.ToChar(bb[i]);
}
switch (a)
{
case "time":
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(DateTime.Now.TimeOfDay.ToString());
stm.Write(ba, 0, ba.Length);
break;
default:
break;
}
}
这段代码运行后 我们在Server端输入 time 就可以得到对方的系统时间 当然你可以在switch (a)
{
case "time":
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(DateTime.Now.TimeOfDay.ToString());
stm.Write(ba, 0, ba.Length);
break;
default:
break;
}
这里多加些case来处理不同的命令来做更多的事 比如 关闭计算机 得到当前的进程列表什么的当然你也可以通过修改注册表来实现client 的开机自启动或者让client自己想多个地方复制,比如U盘什么的,就有了自动传播的功能很多功能只要去研究,大家都可以去实现
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!