2014-04-22 12:52:00 weixin_30616969 阅读数 38
  • 第09章-局域网技术

    本课内容如下: 1 局域网概述 2 局域网拓扑结构 3 标准以太网(10Base以太网) 4 以太网 5 交换式以太网 6 千兆以太网 7 无线局域网 8 令牌环网 9 FDDI工作机制 10 局域网常见的技术

    2169 人正在学习 去看看 深博

本软件是基于大学寝室局域网聊天的思路。c#源代码如下:



  1  using System;
  2 using System.Drawing;
  3 using System.Collections;
  4 using System.ComponentModel;
  5 using System.Windows.Forms;
  6 using System.Data;
  7 using System.Threading;
  8 using System.Net.Sockets;
  9 using System.IO;
 10 //Download by http://www.codefans.net
 11 namespace SimpleChat
 12 {
 13     /// <summary>
 14     /// Form1 的摘要说明。
 15     /// </summary>
 16     public class MainForm : System.Windows.Forms.Form
 17     {
 18         /// <summary>
 19         /// 必需的设计器变量。
 20         /// </summary>
 21         private System.ComponentModel.Container components = null;
 22         private Thread Listener;
 23         private System.Windows.Forms.Label label1;
 24         private System.Windows.Forms.RichTextBox richTextBox1;
 25         private System.Windows.Forms.Label label2;
 26         private System.Windows.Forms.Button button1;
 27         private System.Windows.Forms.RichTextBox richTextBox2;
 28         private System.Windows.Forms.Label label3;
 29         private System.Windows.Forms.GroupBox groupBox1;
 30         private System.Windows.Forms.TextBox IP;
 31         private System.Windows.Forms.Label label4;
 32         private System.Windows.Forms.TextBox NickName;
 33         private System.Windows.Forms.GroupBox groupBox2;
 34         private System.Windows.Forms.Splitter splitter1;
 35         private System.Windows.Forms.GroupBox groupBox3;
 36         private System.Windows.Forms.Splitter splitter2;
 37         private System.Windows.Forms.Button button2;
 38         private TcpListener TcpListener;
 39         private Label label5;
 40         private ComboBox comboBox1;
 41         private Label label6;
 42         private ComboBox comboBox2;
 43         private Thread sends;
 44 
 45         public MainForm()
 46         {
 47             //
 48             // Windows 窗体设计器支持所必需的
 49             //
 50             InitializeComponent();
 51 
 52             //
 53             // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 54             //
 55         }
 56 
 57         /// <summary>
 58         /// 清理所有正在使用的资源。
 59         /// </summary>
 60         protected override void Dispose( bool disposing )
 61         {
 62             if( disposing )
 63             {
 64                 if (components != null) 
 65                 {
 66                     components.Dispose();
 67                 }
 68             }
 69             base.Dispose( disposing );
 70         }
 71 
 72         #region Windows 窗体设计器生成的代码
 73         /// <summary>
 74         /// 设计器支持所需的方法 - 不要使用代码编辑器修改
 75         /// 此方法的内容。
 76         /// </summary>
 77         private void InitializeComponent()
 78         {
 79             System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
 80             this.label1 = new System.Windows.Forms.Label();
 81             this.richTextBox1 = new System.Windows.Forms.RichTextBox();
 82             this.label2 = new System.Windows.Forms.Label();
 83             this.button1 = new System.Windows.Forms.Button();
 84             this.richTextBox2 = new System.Windows.Forms.RichTextBox();
 85             this.label3 = new System.Windows.Forms.Label();
 86             this.groupBox1 = new System.Windows.Forms.GroupBox();
 87             this.NickName = new System.Windows.Forms.TextBox();
 88             this.label4 = new System.Windows.Forms.Label();
 89             this.IP = new System.Windows.Forms.TextBox();
 90             this.groupBox2 = new System.Windows.Forms.GroupBox();
 91             this.splitter1 = new System.Windows.Forms.Splitter();
 92             this.groupBox3 = new System.Windows.Forms.GroupBox();
 93             this.label5 = new System.Windows.Forms.Label();
 94             this.comboBox1 = new System.Windows.Forms.ComboBox();
 95             this.splitter2 = new System.Windows.Forms.Splitter();
 96             this.button2 = new System.Windows.Forms.Button();
 97             this.label6 = new System.Windows.Forms.Label();
 98             this.comboBox2 = new System.Windows.Forms.ComboBox();
 99             this.groupBox1.SuspendLayout();
100             this.groupBox2.SuspendLayout();
101             this.groupBox3.SuspendLayout();
102             this.SuspendLayout();
103             // 
104             // label1
105             // 
106             this.label1.Location = new System.Drawing.Point(8, 17);
107             this.label1.Name = "label1";
108             this.label1.Size = new System.Drawing.Size(80, 15);
109             this.label1.TabIndex = 0;
110             this.label1.Text = "对方IP地址:";
111             // 
112             // richTextBox1
113             // 
114             this.richTextBox1.BackColor = System.Drawing.SystemColors.HighlightText;
115             this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
116             this.richTextBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
117             this.richTextBox1.Location = new System.Drawing.Point(3, 39);
118             this.richTextBox1.Name = "richTextBox1";
119             this.richTextBox1.Size = new System.Drawing.Size(478, 110);
120             this.richTextBox1.TabIndex = 1;
121             this.richTextBox1.Text = "";
122             // 
123             // label2
124             // 
125             this.label2.Dock = System.Windows.Forms.DockStyle.Top;
126             this.label2.Location = new System.Drawing.Point(3, 17);
127             this.label2.Name = "label2";
128             this.label2.Size = new System.Drawing.Size(478, 19);
129             this.label2.TabIndex = 2;
130             this.label2.Text = "输入框:";
131             // 
132             // button1
133             // 
134             this.button1.Location = new System.Drawing.Point(0, 352);
135             this.button1.Name = "button1";
136             this.button1.Size = new System.Drawing.Size(75, 23);
137             this.button1.TabIndex = 3;
138             this.button1.Text = "发送";
139             this.button1.Click += new System.EventHandler(this.button1_Click);
140             // 
141             // richTextBox2
142             // 
143             this.richTextBox2.BackColor = System.Drawing.SystemColors.HighlightText;
144             this.richTextBox2.Dock = System.Windows.Forms.DockStyle.Fill;
145             this.richTextBox2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
146             this.richTextBox2.Location = new System.Drawing.Point(3, 36);
147             this.richTextBox2.Name = "richTextBox2";
148             this.richTextBox2.Size = new System.Drawing.Size(478, 121);
149             this.richTextBox2.TabIndex = 4;
150             this.richTextBox2.Text = "";
151             // 
152             // label3
153             // 
154             this.label3.Dock = System.Windows.Forms.DockStyle.Top;
155             this.label3.Location = new System.Drawing.Point(3, 17);
156             this.label3.Name = "label3";
157             this.label3.Size = new System.Drawing.Size(478, 16);
158             this.label3.TabIndex = 5;
159             this.label3.Text = "聊天信息:";
160             // 
161             // groupBox1
162             // 
163             this.groupBox1.Controls.Add(this.NickName);
164             this.groupBox1.Controls.Add(this.label4);
165             this.groupBox1.Controls.Add(this.IP);
166             this.groupBox1.Controls.Add(this.label1);
167             this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top;
168             this.groupBox1.Location = new System.Drawing.Point(0, 0);
169             this.groupBox1.Name = "groupBox1";
170             this.groupBox1.Size = new System.Drawing.Size(484, 40);
171             this.groupBox1.TabIndex = 6;
172             this.groupBox1.TabStop = false;
173             // 
174             // NickName
175             // 
176             this.NickName.Location = new System.Drawing.Point(308, 13);
177             this.NickName.Name = "NickName";
178             this.NickName.Size = new System.Drawing.Size(110, 21);
179             this.NickName.TabIndex = 3;
180             // 
181             // label4
182             // 
183             this.label4.Location = new System.Drawing.Point(247, 16);
184             this.label4.Name = "label4";
185             this.label4.Size = new System.Drawing.Size(70, 18);
186             this.label4.TabIndex = 2;
187             this.label4.Text = "你的昵称:";
188             // 
189             // IP
190             // 
191             this.IP.Location = new System.Drawing.Point(85, 14);
192             this.IP.Name = "IP";
193             this.IP.Size = new System.Drawing.Size(100, 21);
194             this.IP.TabIndex = 1;
195             // 
196             // groupBox2
197             // 
198             this.groupBox2.Controls.Add(this.richTextBox2);
199             this.groupBox2.Controls.Add(this.splitter1);
200             this.groupBox2.Controls.Add(this.label3);
201             this.groupBox2.Dock = System.Windows.Forms.DockStyle.Top;
202             this.groupBox2.Location = new System.Drawing.Point(0, 40);
203             this.groupBox2.Name = "groupBox2";
204             this.groupBox2.Size = new System.Drawing.Size(484, 160);
205             this.groupBox2.TabIndex = 7;
206             this.groupBox2.TabStop = false;
207             // 
208             // splitter1
209             // 
210             this.splitter1.Dock = System.Windows.Forms.DockStyle.Top;
211             this.splitter1.Location = new System.Drawing.Point(3, 33);
212             this.splitter1.Name = "splitter1";
213             this.splitter1.Size = new System.Drawing.Size(478, 3);
214             this.splitter1.TabIndex = 6;
215             this.splitter1.TabStop = false;
216             // 
217             // groupBox3
218             // 
219             this.groupBox3.Controls.Add(this.label5);
220             this.groupBox3.Controls.Add(this.comboBox1);
221             this.groupBox3.Controls.Add(this.richTextBox1);
222             this.groupBox3.Controls.Add(this.splitter2);
223             this.groupBox3.Controls.Add(this.label2);
224             this.groupBox3.Dock = System.Windows.Forms.DockStyle.Top;
225             this.groupBox3.Location = new System.Drawing.Point(0, 200);
226             this.groupBox3.Name = "groupBox3";
227             this.groupBox3.Size = new System.Drawing.Size(484, 152);
228             this.groupBox3.TabIndex = 8;
229             this.groupBox3.TabStop = false;
230             // 
231             // label5
232             // 
233             this.label5.AutoSize = true;
234             this.label5.Location = new System.Drawing.Point(139, 17);
235             this.label5.Name = "label5";
236             this.label5.Size = new System.Drawing.Size(65, 12);
237             this.label5.TabIndex = 5;
238             this.label5.Text = "常用短语:";
239             // 
240             // comboBox1
241             // 
242             this.comboBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
243             this.comboBox1.Font = new System.Drawing.Font("华文新魏", 8.999999F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
244             this.comboBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
245             this.comboBox1.FormattingEnabled = true;
246             this.comboBox1.Items.AddRange(new object[] {
247             "你好,逗比 >=<",
248             "我在忙,等会回复你。",
249             "额心情不好,表惹我!!!",
250             "F-U-C-K !",
251             "贱人,且行且珍惜。。。。",
252             "因为你长的太丑,系统拒绝发送你的信息^-^",
253             "不是我不说话,我一说话就把我的智商暴露了。~(*^__^*) 嘻嘻…"});
254             this.comboBox1.Location = new System.Drawing.Point(222, 15);
255             this.comboBox1.Name = "comboBox1";
256             this.comboBox1.Size = new System.Drawing.Size(211, 20);
257             this.comboBox1.TabIndex = 4;
258             this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
259             // 
260             // splitter2
261             // 
262             this.splitter2.Dock = System.Windows.Forms.DockStyle.Top;
263             this.splitter2.Location = new System.Drawing.Point(3, 36);
264             this.splitter2.Name = "splitter2";
265             this.splitter2.Size = new System.Drawing.Size(478, 3);
266             this.splitter2.TabIndex = 3;
267             this.splitter2.TabStop = false;
268             // 
269             // button2
270             // 
271             this.button2.Location = new System.Drawing.Point(397, 354);
272             this.button2.Name = "button2";
273             this.button2.Size = new System.Drawing.Size(75, 23);
274             this.button2.TabIndex = 9;
275             this.button2.Text = "关于";
276             this.button2.Click += new System.EventHandler(this.button2_Click);
277             // 
278             // label6
279             // 
280             this.label6.AutoSize = true;
281             this.label6.Location = new System.Drawing.Point(136, 357);
282             this.label6.Name = "label6";
283             this.label6.Size = new System.Drawing.Size(65, 12);
284             this.label6.TabIndex = 10;
285             this.label6.Text = "常用表情:";
286             // 
287             // comboBox2
288             // 
289             this.comboBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));
290             this.comboBox2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
291             this.comboBox2.FormattingEnabled = true;
292             this.comboBox2.Items.AddRange(new object[] {
293             "\\^o^/ 欢呼",
294             "",
295             "*^?^* 笑,打",
296             "",
297             "::>_<:: 哭 ",
298             "",
299             "@x@ 生气",
300             "",
301             "( ^_^ )? 什麼意思??",
302             "",
303             "O_o 惊讶~~~",
304             "",
305             "^◎- 爱你呦~~",
306             "",
307             "得意 <( ̄︶ ̄)>",
308             "",
309             " 乾杯 []~( ̄▽ ̄)~*",
310             "",
311             "滿足 ( ̄ˇ ̄)  ",
312             "",
313             "沒睡醒 ( ̄﹏ ̄)  ",
314             "",
315             "狡猾(‵﹏′) ",
316             "",
317             "被打一巴掌 ( ̄ε(# ̄)",
318             "  ",
319             "無言 ( ̄. ̄)  ",
320             "",
321             "無奈 ╮( ̄▽ ̄)╭  ",
322             "",
323             "裝傻 ( ̄▽ ̄)~* ",
324             "",
325             "驚訝 (⊙ˍ⊙)",
326             "",
327             "發現( ̄. ̄)+ ",
328             " ",
329             "驚嚇 Σ( ° △ °|||)︴  ",
330             "",
331             "冷 ( ̄▽ ̄)\"  ",
332             "",
333             "沒辦法 ╮(╯▽╰)╭ ",
334             "",
335             "貓咪臉 (= ̄ω ̄=)  ",
336             "",
337             "疑惑 ( ̄3 ̄)a  ",
338             "",
339             "阿達 ( ̄0  ̄)y  ",
340             "",
341             "重創 (。_。)  ",
342             "",
343             "不 (>﹏<) ",
344             "",
345             "懷疑 (→_→)  ",
346             "",
347             "睏 ( ̄o ̄) . z Z  ",
348             "",
349             "崇拜 m( _ _ )m  ",
350             "",
351             "我想想 (ˇˍˇ)  ",
352             "",
353             "生氣 <( ̄ ﹌  ̄)> "});
354             this.comboBox2.Location = new System.Drawing.Point(207, 354);
355             this.comboBox2.Name = "comboBox2";
356             this.comboBox2.Size = new System.Drawing.Size(125, 20);
357             this.comboBox2.TabIndex = 11;
358             this.comboBox2.SelectedIndexChanged += new System.EventHandler(this.comboBox2_SelectedIndexChanged);
359             // 
360             // MainForm
361             // 
362             this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
363             this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
364             this.ClientSize = new System.Drawing.Size(484, 377);
365             this.Controls.Add(this.comboBox2);
366             this.Controls.Add(this.label6);
367             this.Controls.Add(this.button2);
368             this.Controls.Add(this.groupBox3);
369             this.Controls.Add(this.groupBox2);
370             this.Controls.Add(this.groupBox1);
371             this.Controls.Add(this.button1);
372             this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
373             this.MaximumSize = new System.Drawing.Size(500, 416);
374             this.Name = "MainForm";
375             this.RightToLeftLayout = true;
376             this.Text = "HPU-计算机11-4 局域网聊天";
377             this.Closed += new System.EventHandler(this.MainForm_Closed);
378             this.Load += new System.EventHandler(this.MainForm_Load);
379             this.groupBox1.ResumeLayout(false);
380             this.groupBox1.PerformLayout();
381             this.groupBox2.ResumeLayout(false);
382             this.groupBox3.ResumeLayout(false);
383             this.groupBox3.PerformLayout();
384             this.ResumeLayout(false);
385             this.PerformLayout();
386 
387         }
388         #endregion
389 
390         /// <summary>
391         /// 应用程序的主入口点。
392         /// </summary>
393         [STAThread]
394         static void Main() 
395         {
396             Application.Run(new MainForm());
397         }
398         private void StartListen()
399         {
400             this.TcpListener = new TcpListener(19808);
401             this.TcpListener.Start();
402             while( true )
403             {
404                 TcpClient TcpClient = this.TcpListener.AcceptTcpClient();
405                 NetworkStream MyStream = TcpClient.GetStream();
406                 byte [] bytes = new byte[2048];
407                 int bytesRead = MyStream.Read(bytes,0,bytes.Length);
408                 string message = System.Text.Encoding.UTF8.GetString(bytes,0,bytesRead);
409                 this.richTextBox2.Text += message + "\n";
410             }
411         }
412 
413         private void MainForm_Load(object sender, System.EventArgs e)
414         {
415             this.Listener = new Thread(new ThreadStart(StartListen));
416             this.Listener.Start();
417         }
418 
419         private void MainForm_Closed(object sender, System.EventArgs e)
420         {
421             if ( this.Listener != null )
422                 this.Listener.Abort();
423             if ( this.TcpListener != null )
424                 this.TcpListener.Stop();
425         }
426 
427         private void button1_Click(object sender, System.EventArgs e)
428         {
429             if ( sends == null || !sends.IsAlive)
430             {
431                 sends = new Thread(new ThreadStart(send));
432                 sends.Start();
433             }
434             else
435                 MessageBox.Show("发送过快!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
436         }
437 
438         private void button2_Click(object sender, System.EventArgs e)
439         {
440             MessageBox.Show("制作:HPU 计算机11-4 魏春生\n输入对方IP地址,只要双方都打开本程序即可聊天...\n HpuChat v1.0");
441         }
442 
443         private void send()
444         {
445             if (this.IP.Text.Length < 7 )
446             {
447                 MessageBox.Show("IP地址错误!","错误信息:",MessageBoxButtons.OK,MessageBoxIcon.Information);
448                 return;
449             }
450             if ( this.richTextBox1.Text.Length < 1 )
451             {
452                 return;
453             }
454             try
455             {
456                 string Message = this.NickName.Text + ":" + "   " + DateTime.Now.ToString() + "\n" + "   " + this.richTextBox1.Text + "\n"; 
457                 TcpClient TcpClient = new TcpClient(this.IP.Text, 19808);
458                 NetworkStream tcpStream = TcpClient.GetStream();
459                 StreamWriter stream = new StreamWriter(tcpStream);
460                 stream.Flush();
461                 stream.Write(Message);
462                 stream.Close();
463                 TcpClient.Close();
464                 this.richTextBox2.AppendText( Message + "\n");
465                 richTextBox1.Text = string.Empty;
466             }
467             catch ( Exception Err)
468             {
469                 MessageBox.Show(Err.Message,"错误信息:",MessageBoxButtons.OK,MessageBoxIcon.Information);
470             }
471             finally
472             {
473                 sends.Abort();
474             }
475            
476     }
477 
478         private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
479         {
480             this.richTextBox1.Text = comboBox1.SelectedItem.ToString();
481         }
482 
483         private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
484         {
485             this.richTextBox1.Text = comboBox2.SelectedItem.ToString();
486         }
487     }
488 }
View Code

 




功能比较简单。只能文本聊天,没有表情。有待改善。
软件截图::::::
使用说明书地址::

 

转载于:https://www.cnblogs.com/spring87/p/3680274.html

2019-09-06 16:56:34 lclcsdnblink 阅读数 230
  • 第09章-局域网技术

    本课内容如下: 1 局域网概述 2 局域网拓扑结构 3 标准以太网(10Base以太网) 4 以太网 5 交换式以太网 6 千兆以太网 7 无线局域网 8 令牌环网 9 FDDI工作机制 10 局域网常见的技术

    2169 人正在学习 去看看 深博
  • 本程序可以使用ip也可以使用主机名,这样就可以在打包之后,就不需要一直动态修改IP了

服务器端代码:

 public partial class FServer : Form
    {
        public FServer()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }
        Thread threadWatch = null; //负责监听客户端的线程
        Socket socketWatch = null; //负责监听客户端的套接字

        private void BtnServerConn_Click(object sender, EventArgs e)
        {
            bool IsContain = false;
            int[] num = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int i = 0;
            if (txtIP.Text.Contains(num[i].ToString()))
            {
                //定义一个套接字用于监听客户端发来的信息  包含3个参数(IP4寻址协议,流式连接,TCP协议)
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //服务端发送信息 需要1个IP地址和端口号
                IPAddress ipaddress = IPAddress.Parse(txtIP.Text.Trim()); //获取文本框输入的IP地址

                //将IP地址和端口号绑定到网络节点endpoint上 
                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPORT.Text.Trim())); //获取文本框上输入的端口号
                                                                                                 //监听绑定的网络节点
                socketWatch.Bind(endpoint);
                //将套接字的监听队列长度限制为20
                socketWatch.Listen(20);
                //创建一个监听线程 
                threadWatch = new Thread(WatchConnecting);
                //将窗体线程设置为与后台同步
                threadWatch.IsBackground = true;
                //启动线程
                threadWatch.Start();
                //启动线程后 txtMsg文本框显示相应提示
                txtMsg.AppendText("开始监听客户端传来的信息!" + "\r\n");
            }

            else
            {
                //定义一个套接字用于监听客户端发来的信息  包含3个参数(IP4寻址协议,流式连接,TCP协议)
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //服务端发送信息 需要1个IP地址和端口号
                //IPAddress ipaddress = IPAddress.Parse(txtIP.Text.Trim()); //获取文本框输入的IP地址
                IPAddress[] ips = Dns.GetHostAddresses(txtIP.Text.Trim());
                string ic = Convert.ToString(ips[1]);
                IPAddress ipaddress = IPAddress.Parse(ic);
                //将IP地址和端口号绑定到网络节点endpoint上 
                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPORT.Text.Trim())); //获取文本框上输入的端口号
                                                                                                 //监听绑定的网络节点
                socketWatch.Bind(endpoint);
                //将套接字的监听队列长度限制为20
                socketWatch.Listen(20);
                //创建一个监听线程 
                threadWatch = new Thread(WatchConnecting);
                //将窗体线程设置为与后台同步
                threadWatch.IsBackground = true;
                //启动线程
                threadWatch.Start();
                //启动线程后 txtMsg文本框显示相应提示
                txtMsg.AppendText("开始监听客户端传来的信息!" + "\r\n");

            }
        }

        
         

        
        //创建一个负责和客户端通信的套接字 
        Socket socConnection = null;

        /// <summary>
        /// 监听客户端发来的请求
        /// </summary>
        private void WatchConnecting()
        {
            while (true)  //持续不断监听客户端发来的请求
            {
                socConnection = socketWatch.Accept();
                txtMsg.AppendText("客户端连接成功" + "\r\n");
                //创建一个通信线程 
                ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);
                Thread thr = new Thread(pts);
                thr.IsBackground = true;
                //启动线程
                thr.Start(socConnection);
            }
        }

        /// <summary>
        /// 发送信息到客户端的方法
        /// </summary>
        /// <param name="sendMsg">发送的字符串信息</param>
        private void ServerSendMsg(string sendMsg)
        {
            //将输入的字符串转换成 机器可以识别的字节数组
            byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendMsg);
            //向客户端发送字节数组信息
            socConnection.Send(arrSendMsg);
            //将发送的字符串信息附加到文本框txtMsg上
            txtMsg.AppendText("So-flash:" + GetCurrentTime() + "\r\n" + sendMsg + "\r\n");
        }

        /// <summary>
        /// 接收客户端发来的信息 
        /// </summary>
        /// <param name="socketClientPara">客户端套接字对象</param>
        private void ServerRecMsg(object socketClientPara)
        {
            Socket socketServer = socketClientPara as Socket;
            while (true)
            {
                //创建一个内存缓冲区 其大小为1024*1024字节  即1M
                byte[] arrServerRecMsg = new byte[1024 * 1024];
                //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
                int length = socketServer.Receive(arrServerRecMsg);
                //将机器接受到的字节数组转换为人可以读懂的字符串
                string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
                //将发送的字符串信息附加到文本框txtMsg上  
                txtMsg.AppendText("天之涯:" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n");
            }
        }

        private void BtnSendMsg_Click(object sender, EventArgs e)
        {
            //调用 ServerSendMsg方法  发送信息到客户端
            ServerSendMsg(txtSendMsg.Text.Trim());
        }

        private void TxtSendMsg_KeyDown(object sender, KeyEventArgs e)
        {
            //如果用户按下了Enter键
            if (e.KeyCode == Keys.Enter)
            {
                //则调用 服务器向客户端发送信息的方法
                ServerSendMsg(txtSendMsg.Text.Trim());
            }
        }
        /// <summary>
        /// 获取当前系统时间的方法
        /// </summary>
        /// <returns>当前时间</returns>
        private DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }

    }

客户端代码:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //关闭对文本框的非法线程操作检查
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }
        //创建 1个客户端套接字 和1个负责监听服务端请求的线程  
        Socket socketClient = null;
        Thread threadClient = null;

        private void BtnBeginListen_Click(object sender, EventArgs e)
        {
            bool IsContain = false;
            int[] num = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int i = 0;
            if (txtIP.Text.Contains(num[i].ToString()))
            {
                //定义一个套字节监听  包含3个参数(IP4寻址协议,流式连接,TCP协议)
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //需要获取文本框中的IP地址
                IPAddress ipaddress = IPAddress.Parse(txtIP.Text.Trim());
                //将获取的ip地址和端口号绑定到网络节点endpoint上
                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPort.Text.Trim()));
                //这里客户端套接字连接到网络节点(服务端)用的方法是Connect 而不是Bind
                socketClient.Connect(endpoint);
                //创建一个线程 用于监听服务端发来的消息
                threadClient = new Thread(RecMsg);
                //将窗体线程设置为与后台同步
                threadClient.IsBackground = true;
                //启动线程
                threadClient.Start();
            }
            else
            {
                //定义一个套字节监听  包含3个参数(IP4寻址协议,流式连接,TCP协议)
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //需要获取文本框中的IP地址                
                IPAddress[] ips = Dns.GetHostAddresses(txtIP.Text.Trim());
                string ic = Convert.ToString(ips[1]);
                IPAddress ipaddress = IPAddress.Parse(ic);
                //将获取的ip地址和端口号绑定到网络节点endpoint上
                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPort.Text.Trim()));
                //这里客户端套接字连接到网络节点(服务端)用的方法是Connect 而不是Bind
                socketClient.Connect(endpoint);
                //创建一个线程 用于监听服务端发来的消息
                threadClient = new Thread(RecMsg);
                //将窗体线程设置为与后台同步
                threadClient.IsBackground = true;
                //启动线程
                threadClient.Start();
            }
        }
        /// <summary>
        /// 接收服务端发来信息的方法
        /// </summary>
        private void RecMsg()
        {
            while (true) //持续监听服务端发来的消息
            {
                //定义一个1M的内存缓冲区 用于临时性存储接收到的信息
                byte[] arrRecMsg = new byte[1024 * 1024];
                //将客户端套接字接收到的数据存入内存缓冲区, 并获取其长度
                int length = socketClient.Receive(arrRecMsg);
                //将套接字获取到的字节数组转换为人可以看懂的字符串
                string strRecMsg = Encoding.UTF8.GetString(arrRecMsg, 0, length);
                //将发送的信息追加到聊天内容文本框中
                txtMsg.AppendText("So-flash:" + GetCurrentTime() + "\r\n" + strRecMsg + "\r\n");
            }
        }

        /// <summary>
        /// 发送字符串信息到服务端的方法
        /// </summary>
        /// <param name="sendMsg">发送的字符串信息</param>
        private void ClientSendMsg(string sendMsg)
        {
            //将输入的内容字符串转换为机器可以识别的字节数组
            byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
            //调用客户端套接字发送字节数组
            socketClient.Send(arrClientSendMsg);
            //将发送的信息追加到聊天内容文本框中
            txtMsg.AppendText("天之涯:" + GetCurrentTime() + "\r\n" + sendMsg + "\r\n");
        }

        private void BtnSend_Click(object sender, EventArgs e)
        {
            //调用ClientSendMsg方法 将文本框中输入的信息发送给服务端
            ClientSendMsg(txtCMsg.Text.Trim());
        }

        private void TxtCMsg_KeyDown(object sender, KeyEventArgs e)
        {
            //当光标位于文本框时 如果用户按下了键盘上的Enter键 
            if (e.KeyCode == Keys.Enter)
            {
                //则调用客户端向服务端发送信息的方法
                ClientSendMsg(txtCMsg.Text.Trim());
            }
        }
        /// <summary>
        /// 获取当前系统时间的方法
        /// </summary>
        /// <returns>当前时间</returns>
        private DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }
    }

将主机名转换为IP的核心代码:

 IPAddress[] ips = Dns.GetHostAddresses(txtIP.Text.Trim());

上面的代码需要将IPAddress[]转化为IPAddress,以下的代码便可以实现

IPAddress[] ips = Dns.GetHostAddresses(txtIP.Text.Trim());
                string ic = Convert.ToString(ips[1]);
                IPAddress ipaddress = IPAddress.Parse(ic);
                //将IP地址和端口号绑定到网络节点endpoint上 
                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPORT.Text.Trim())); //获取文本框上输入的端口号
                                                                                                 //监听绑定的网络节点

 

2013-03-11 10:27:20 smartsmile2012 阅读数 2816
  • 第09章-局域网技术

    本课内容如下: 1 局域网概述 2 局域网拓扑结构 3 标准以太网(10Base以太网) 4 以太网 5 交换式以太网 6 千兆以太网 7 无线局域网 8 令牌环网 9 FDDI工作机制 10 局域网常见的技术

    2169 人正在学习 去看看 深博
        //发送大量文本消息
        private void sendMessage()
        {
            if (richTextBox_send.Text.Trim().Length==0 && richTextBox_send.Rtf.IndexOf("pict")<0)
            {
                MessageBox.Show("发送的消息不能为空");
                return;
            }
            
            if (Encoding.Default.GetByteCount(richTextBox_send.Text) > 1024*3)
                {
                    MessageBox.Show("发送的内容过长");
                    return;
                }
            try
            {
                //初始化接受套接字:寻址方案,以字符流方式和Tcp通信
                socketSent = new Socket(AddressFamily.InterNetwork,
                               SocketType.Stream,
                               ProtocolType.Tcp);

                //设置目标服务器IP地址和端口
                ipSent = new IPEndPoint(IPAddress.Parse(ip), 8001);

                //与目标服务器进行连接
                socketSent.Connect(ipSent);
                
                //将要发送的消息转化为字节流,然后发送
                

                socketSent.Send(Encoding.Default.GetBytes("MSG"));
                Thread.Sleep(100);
                //循环发送
                //设置缓冲区为1024byte
                byte[] buff = new byte[1024];
                int len = 0;
                MemoryStream data = new MemoryStream();
                richTextBox_accept.Rtf = richTextBox_accept.Rtf.Replace(@"\f1\par", "");
                richTextBox_send.SaveFile(data, RichTextBoxStreamType.RichText);
                data.Position = 0;
                while ((len = data.Read(buff, 0, 1024)) != 0)
                {
                    //按实际的字节总量发送信息
                    socketSent.Send(buff, 0, len, SocketFlags.None);
                    //richTextBox_accept.AppendText(Encoding.Default.GetString(buff));
                }
                data.Close();
                data.Dispose();
                socketSent.Send(Encoding.Default.GetBytes("END"));
                socketSent.Close();
            }
            catch
            {
                MessageBox.Show(user + "已经下线!");
                return;
            }
            if (richTextBox_accept.Text != "")
            {
                richTextBox_accept.SelectionColor = Color.Green;
                richTextBox_accept.AppendText("\n" + currentUser + " " + DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss") + "\n");
                richTextBox_accept.SelectionColor = Color.Black;

                richTextBox_accept.Select(richTextBox_accept.Text.Length, 0);
                richTextBox_accept.SelectedRtf = richTextBox_send.Rtf;
                richTextBox_accept.Update();
                richTextBox_accept.Select(richTextBox_accept.Rtf.Length, 0);
            }
            else
            {
                richTextBox_accept.SelectionColor = Color.Green;
                richTextBox_accept.AppendText(currentUser + " " + DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss") + "\n");
                richTextBox_accept.SelectionColor = Color.Black;

                richTextBox_accept.Select(richTextBox_accept.Text.Length, 0);
                richTextBox_accept.SelectedRtf = richTextBox_send.Rtf;
                richTextBox_accept.Update();
                richTextBox_accept.Select(richTextBox_accept.Rtf.Length, 0);

            }
            this.richTextBox_send.Clear();
            richTextBox_accept.ScrollToCaret();
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //组合键发送消息
        private void richTextBox_send_KeyUp(object sender, KeyEventArgs e)
        {
            if ((Control.ModifierKeys & Keys.Control) != 0 && e.KeyCode == Keys.Enter)
            {
                if (radioBtn_sendStyle2.Checked)//发送模式选择为Enter+Ctrl
                { sendMessage(); }
            }
            else if (e.KeyCode == Keys.Enter)
            {
                if (radioBtn_sendStyle1.Checked)//发送模式选择为Enter
                {
                    sendMessage();
                }
            }
        }

2016-04-12 22:48:00 anyan9579 阅读数 13
  • 第09章-局域网技术

    本课内容如下: 1 局域网概述 2 局域网拓扑结构 3 标准以太网(10Base以太网) 4 以太网 5 交换式以太网 6 千兆以太网 7 无线局域网 8 令牌环网 9 FDDI工作机制 10 局域网常见的技术

    2169 人正在学习 去看看 深博

 

一个基于c#的点对点局域网文件传输小案例,运行效果截图

//界面窗体

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 文件传输
{
public partial class Form1 : Form
{
/// <summary>
/// 文件名
/// </summary>
private string fileName;
/// <summary>
/// 文件路径
/// </summary>
private string filePath;
/// <summary>
/// 文件大小
/// </summary>
private long fileSize;
public Form1()
{
InitializeComponent();
Thread.CurrentThread.IsBackground=true;
textBox2.Text = IpUtil.GetLocalIp();
label1.Text = "您的ip:" + IpUtil.GetLocalIp() + " 您的端口:" + IpUtil.GetRandomPort();
var s= new FileRecive(this);
new Thread(s.run).Start();
}

/// <summary>
/// 信息提示框
/// </summary>
/// <param name="msg"></param>
public void Tip(string msg) {

MessageBox.Show(msg,"温馨提示");
}

/// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
string ip = textBox2.Text;
string port =textBox3.Text;

if (fileName.Length == 0) {

Tip("请选择文件");
return;
}
if(ip.Length==0||port.ToString().Length==0){

Tip("端口和ip地址是必须的!");
return;
}

var c = new FileSend(this,new string[]{ip,port,fileName,filePath,fileSize.ToString()});
new Thread(c.Send).Start();
}

/// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dig = new OpenFileDialog();

dig.ShowDialog();

//获取文件名
this.fileName = dig.SafeFileName;

//获取文件路径
this.filePath = dig.FileName;

FileInfo f = new FileInfo(this.filePath);

//获取文件大小
this.fileSize = f.Length;
textBox1.Text = filePath;
}

/// <summary>
/// 更新进度条
/// </summary>
/// <param name="value"></param>
public void UpDateProgress(int value) {


this.progressBar1.Value=value;
this.label2.Text = value + "%";
System.Windows.Forms.Application.DoEvents();
}

/// <summary>
/// 修改状态
/// </summary>
/// <param name="state"></param>
public void SetState(string state) {

label5.Text = state;
}
/// <summary>
/// 退出程序
/// </summary>
public void Exit() {

Application.Exit();
}
}
}

//ip和端口工具类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace 文件传输
{
class IpUtil
{
/// <summary>
/// 获取本地ip地址
/// </summary>
/// <returns></returns>
public static string GetLocalIp()
{
string hostname = Dns.GetHostName();
IPHostEntry localhost = Dns.GetHostByName(hostname);
IPAddress localaddr = localhost.AddressList[0];
return localaddr.ToString();
}

/// <summary>
/// 产生随机端口
/// </summary>
/// <returns></returns>
public static int GetRandomPort() {


return new Random().Next(1000)+5000;
}
}
}

//文件发送类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace 文件传输
{

//文件发送类
class FileSend
{
private TcpClient client;
private NetworkStream stream;
private string[] param;
private Form1 fm;
public FileSend(Form1 fm,params string[] param) {

this.param = param;
this.fm = fm;

}

public void Send()
{

try
{
//连接接收端
this.client = new TcpClient(param[0], int.Parse(param[1]));
string msg = param[2] + "|" + param[4];
byte[] m = Encoding.UTF8.GetBytes(msg);

while (true){
this.stream = this.client.GetStream();
this.stream.Write(m, 0, m.Length);
this.stream.Flush();
byte[] data = new byte[1024];
int len = this.stream.Read(data, 0, data.Length);
msg = Encoding.UTF8.GetString(data, 0, len);
//对方要接收我发送的文件
if (msg.Equals("1"))
{

fm.SetState("正在发送:");
FileStream os = new FileStream(param[3], FileMode.OpenOrCreate);

data = new byte[1024];
//记录当前发送进度
long currentprogress = 0;
len=0;
while ((len = os.Read(data, 0, data.Length)) > 0) {
currentprogress += len;
//更新进度条
fm.UpDateProgress((int)(currentprogress*100/long.Parse(param[4])));
this.stream.Write(data,0,len);

}
os.Flush();
this.stream.Flush();
os.Close();
this.stream.Close();
fm.Tip("发送成功!");
fm.Exit();
}
}
}
catch (Exception e)
{

fm.Tip(e.Message);

}

}
}
}

 

//文件接收类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 文件传输
{

/// <summary>
/// 文件接收类
/// </summary>
class FileRecive
{

private TcpListener server;
private Form1 fm;
private NetworkStream stream;
public FileRecive(Form1 fm) {
this.fm = fm;
try
{
this.server = new TcpListener(IPAddress.Parse(IpUtil.GetLocalIp()), IpUtil.GetRandomPort());

server.Start();
}
catch (Exception e) {

fm.Tip(e.Message);

}
}

/// <summary>
/// 接收文件
/// </summary>
public void run()
{


while (true)
{
try
{
TcpClient client = server.AcceptTcpClient();
this.stream = client.GetStream();
byte[] msgs = new byte[1024];

int len = this.stream.Read(msgs, 0, msgs.Length);

string msg = Encoding.UTF8.GetString(msgs, 0, len);

string[] tip = msg.Split('|');
if (DialogResult.Yes == MessageBox.Show(IpUtil.GetLocalIp() + "给您发了一个文件:" + tip[0] + "大小为:" + (long.Parse(tip[1]) / 1024) + "kb ,确定要接收吗?", "接收提醒", MessageBoxButtons.YesNo))
{

//将接收信息反馈给发送方
msg = "1";
msgs = Encoding.UTF8.GetBytes(msg);
this.stream.Write(msgs, 0, msgs.Length);
this.stream.Flush();
fm.SetState("正在接收:");
//开始接收文件
string path = @"C:\Users\Administrator\Desktop\" + tip[0];//接收文件的存储路径
FileStream os = new FileStream(path, FileMode.OpenOrCreate);

byte[] data = new byte[1024];
long currentprogress = 0;
int length = 0;
while ((length = this.stream.Read(data, 0, data.Length)) > 0)
{
currentprogress += length;
//更新进度条
fm.UpDateProgress((int)(currentprogress * 100 / long.Parse(tip[1])));
os.Write(data, 0, length);

}
os.Flush();
this.stream.Flush();
os.Close();
this.stream.Close();
fm.Tip("成功接收文件并存入了" + path + "中!");
fm.Exit();

}

}
catch (Exception e)
{
fm.Tip(e.Message);

}
}
}
}
}

 

转载于:https://www.cnblogs.com/zzjbk/p/5384911.html

2008-03-24 16:36:00 wxg22526451 阅读数 1062
  • 第09章-局域网技术

    本课内容如下: 1 局域网概述 2 局域网拓扑结构 3 标准以太网(10Base以太网) 4 以太网 5 交换式以太网 6 千兆以太网 7 无线局域网 8 令牌环网 9 FDDI工作机制 10 局域网常见的技术

    2169 人正在学习 去看看 深博
using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.IO; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Security.Principal; 
using System.Runtime.InteropServices; 

namespace WebApplication1 

    
public partial class _Default : System.Web.UI.Page 
    

        
public const int LOGON32_LOGON_INTERACTIVE = 2
        
public const int LOGON32_PROVIDER_DEFAULT = 0

        WindowsImpersonationContext impersonationContext; 

        [DllImport(
"advapi32.dll", CharSet = CharSet.Auto)] 
        
public static extern int LogonUser(String lpszUserName, 
                                  String lpszDomain, 
                                  String lpszPassword, 
                                  
int dwLogonType, 
                                  
int dwLogonProvider, 
                                  
ref IntPtr phToken); 
        [DllImport(
"advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
        
public extern static int DuplicateToken(IntPtr hToken, 
                                 
int impersonationLevel, 
                                 
ref IntPtr hNewToken); 
        
private bool impersonateValidUser(String userName, String domain, String password) 
        


            IntPtr token 
= IntPtr.Zero; 
            IntPtr tokenDuplicate 
= IntPtr.Zero; 

            
if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0
            

                
if (DuplicateToken(token, 2ref tokenDuplicate) != 0
                

                    WindowsIdentity tempWindowsIdentity; 
                    tempWindowsIdentity 
= new WindowsIdentity(tokenDuplicate); 
                    impersonationContext 
= tempWindowsIdentity.Impersonate(); 
                    
if (impersonationContext != null
                        
return true
                    
else 
                        
return false
                }
 
                
else 
                    
return false
            }
 
            
else 
                
return false
        }
 
        
private void undoImpersonation() 
        

            impersonationContext.Undo();
//回退为未更改前账户 
        }
 
        
protected void Page_Load(object sender, EventArgs e) 
        

            
//临时更改为 跟 网络硬盘相同用户名密码的账户(此账户必须在网络盘有写入权限)本机也需要同样帐号密码的帐户 
            if (impersonateValidUser("administrator""192.168.1.102""kuqu123456")) 
            
{              
                Response.Write(System.IO.File.Exists(
@"/192.168.1.102shareC#高级编程C#高级编程(第四版).pdf"));                
                undoImpersonation(); 
            }
 
            
else 
            

                Response.Write(
"登陆失败");                 
            }
 

        }
 
    }
 
}
 
没有更多推荐了,返回首页