客户端:
namespace NetClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); } IPAddress ip; int port; Thread th; Socket NetClient; /// <summary> /// 连接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOpen_Click(object sender, EventArgs e) { try { ip = IPAddress.Parse(txtAddress.Text); port = Convert.ToInt32(numPort.Value); btnOpen.Enabled = false; th = new Thread(Connection); th.Start(); } catch (Exception ex) { MessageBox.Show("IP地址格式输入不正确!" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void Connection() { NetClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ie = new IPEndPoint(ip, port);//服务器的IP和端口 try { //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。 NetClient.Connect(ie); while (true) { byte[] dt = GetDesktop(); NetClient.Send(dt); dt = null; Thread.Sleep(500); } } catch (SocketException e) { MessageBox.Show("连接失败:" + e.Message); } if (NetClient.Connected) { NetClient.Shutdown(SocketShutdown.Both); NetClient.Close(); } } private byte[] GetDesktop() { Bitmap bmp = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height); using (Graphics g = Graphics.FromImage(bmp)) { g.CopyFromScreen(new Point(0, 0), new Point(0, 0), bmp.Size); } MemoryStream ms = new MemoryStream(); bmp.Save(ms, ImageFormat.Jpeg); byte[] data = new byte[ms.Length]; ms.Position = 0; ms.Read(data, 0, data.Length); ms.Close(); return data; } /// <summary> /// 断开 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnClose_Click(object sender, EventArgs e) { btnOpen.Enabled = true; if (NetClient != null) NetClient.Close(); if (th != null && th.IsAlive) th.Abort(); } } }
服务器端:
namespace NETServer { public delegate void ClientConnectionEventHandler(Socket socket, string ip, bool con); public delegate void DataReceiveEventHandler(byte[] data, string ip); public partial class Form1 : Form { public Form1() { InitializeComponent(); this.ClientConnection += new ClientConnectionEventHandler(Form1_ClientConnection); this.DataReceive += new DataReceiveEventHandler(Form1_DataReceive); } void Form1_DataReceive(byte[] data, string ip) { if (tabControl1.InvokeRequired) { tabControl1.Invoke(new DataReceiveEventHandler(Form1_DataReceive), data, ip); } else { try { TabPage tb = FindTab(ip); if (tb != null) { (tb.Controls[0] as PictureBox).Image = Image.FromStream(new MemoryStream(data)); data = null; } } catch { } } } void Form1_ClientConnection(Socket socket, string ip, bool con) { if (this.InvokeRequired) { this.Invoke(new ClientConnectionEventHandler(Form1_ClientConnection), socket, ip, con); } else { TabPage tp = FindTab(ip); if (con) { Thread th = new Thread(ClientListen); if (tp == null) InitTab(ip, th); th.Start(socket); } else { if (tp != null) { Thread t = tp.Tag as Thread; if (t != null) t.Abort(); tabControl1.TabPages.Remove(tp); } } if (tabControl1.TabPages.Count > 0) this.Text = string.Format("已连接,共有 {0} 个连接...", tabControl1.TabPages.Count); else this.Text = "当前没有客户端连接..."; } } private void InitTab(string ip, Thread th) { TabPage tab = new TabPage(); PictureBox p = new PictureBox(); p.Dock = DockStyle.Fill; p.SizeMode = PictureBoxSizeMode.StretchImage; tab.Controls.Add(p); p.Show(); tab.Tag = th; tab.Text = ip; this.tabControl1.TabPages.Add(tab); } public event ClientConnectionEventHandler ClientConnection; private void ConnectionProxy(Socket socket, string ip, bool con) { if (ClientConnection != null) ClientConnection(socket, ip, con); } public event DataReceiveEventHandler DataReceive; private void ReceiveProxy(byte[] data, string ip) { if (DataReceive != null) DataReceive(data, ip); } Thread th; Socket NetSocket; private void Form1_Load(object sender, EventArgs e) { this.Text = "正在监听,等待客户端连接..."; th = new Thread(InitServer); th.Start(); } private TabPage FindTab(string ip) { foreach (TabPage tp in tabControl1.TabPages) { if (tp.Text == ip) return tp; } return null; } private void InitServer() { int port = 2000; IPAddress ip = null; IPAddress[] id = Dns.GetHostAddresses(""); foreach (IPAddress i in id) { Regex reg = new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"); if (!i.IsIPv6LinkLocal && reg.IsMatch(i.ToString())) { ip = i; break; } } if (ip == null) ip = IPAddress.Parse("127.0.0.1"); IPEndPoint ipep = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint类的新实例 NetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); NetSocket.Bind(ipep); while (true) { NetSocket.Listen(10); Socket client = NetSocket.Accept(); IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint; ConnectionProxy(client, clientip.Address.ToString(), true); } } private void ClientListen(object obj) { Socket client = obj as Socket; if (client == null) return; while (true) {//循环来不断的从客户端获取信息 byte[] data = new byte[200000]; int bf = client.Receive(data); if (bf == 0) { ConnectionProxy(client, ((IPEndPoint)client.RemoteEndPoint).Address.ToString(), false); break; } ReceiveProxy(data, ((IPEndPoint)client.RemoteEndPoint).Address.ToString()); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (NetSocket != null) NetSocket.Close(); if (th != null && th.IsAlive) th.Abort(); if (MessageBox.Show("确定要断开客户端的连接吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) e.Cancel = true; } } }