服務器是干啥子用滴?監聽客戶端,響應客戶端用滴!
雖然是世界上最簡陋的服務器,但是也有幾個注意點:
1.因為要一個死循環監聽客戶端響應,也就是說無法和用戶進行交互了,所以防止前台假死就要為監聽新起一個線程;
2.要把新起的線程td.IsBackground = true;設置為後台線程,這樣的話線程才會隨著應用程序的關閉而關閉,不然的話關了窗體,它還在運行;
3.跨線程問題,在新的線程裡改變UI會報跨線程改變UI的錯誤,所以要用Invoke;
4.在監聽的死循環中加入 Thread.Sleep(1);這樣可以提高應用程序性能,不要擔心當服務的線程正在Sleep的時候來了個請求服務器會收不到,其實是收得到的。
加入Thread.Sleep(1)的CPU如圖:
不加Thread.Sleep(1)的CPU如圖:
所以一定要加!
所以服務器端代碼如下:
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9
10 using System.Threading;
11 using System.Net;
12 using System.Net.Sockets;
13
14
15 namespace Server
16 {
17 public partial class Form1 : Form
18 {
19 public Form1()
20 {
21 InitializeComponent();
22 }
23
24 private void button1_Click(object sender, EventArgs e)
25 {
26 Thread td = new Thread(Listen);
27 td.IsBackground = true;
28 td.Start();
29 this.button1.Enabled = false;
30 MessageBox.Show("服務器成功開啟");
31
32 }
33 public delegate void ChangeRickBoxHandler(RichTextBox rtb,string str);
34 public void ChangeRichTextBox(RichTextBox rtb,string str)
35 {
36 rtb.AppendText(str);
37 }
38 private void Listen()
39 {
40 IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
41 int port = Int32.Parse(this.textBox1.Text.Trim());
42 TcpListener tl = new TcpListener(ip, port);
43 tl.Start();
44 while(true)
45 {
46 if (tl.Pending())
47 {
48 Socket newSocket = tl.AcceptSocket();
49 byte[] buff = new byte[9];
50 int length= newSocket.Receive(buff);
51 string command = Encoding.Default.GetString(buff);
52 if(command == "conServer")
53 {
54 Invoke(new ChangeRickBoxHandler(ChangeRichTextBox),this.richTextBox1,"有客戶端連接了我");
55 }
56 }
57 Thread.Sleep(1);
58 }
59 }
60 }
61 }
62
客戶端代碼:
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9
10 using System.Net;
11 using System.Net.Sockets;
12 using System.Threading;
13
14 namespace Client
15 {
16 public partial class Form1 : Form
17 {
18 public Form1()
19 {
20 InitializeComponent();
21 }
22
23 private void button1_Click(object sender, EventArgs e)
24 {
25 TcpClient tcpClient = new TcpClient();
26 tcpClient.Connect( Dns.GetHostAddresses(Dns.GetHostName())[0], Convert.ToInt32(this.textBox1.Text.Trim().ToString()));
27 NetworkStream nwStream = tcpClient.GetStream();
28 string cmd = "conServer" ;
29 Byte[] bytes = Encoding.Default.GetBytes(cmd.ToCharArray());
30 nwStream.Write(bytes, 0, bytes.Length);
31 }
32 }
33 }
34
出處: http://www.cnblogs.com/zhanglei644213943
源碼下載:http://files.cnblogs.com/zhanglei644213943/世界上最簡陋的服務器.rar