C#通信之Socket通信的简单例子

socket通常也称作”套接字”,用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过”套接字”向网络发出请求或者应答网络请求。

这里构建一个简单的例子,客户端发消息,服务端接收,然后回执一条消息。大致能够了解如何使用Socket进行通信。

服务端监听,接收信息:

客户端连接,并发送信息:

使用Socket通信,程序一般会在幕后运行,然后再合适的时间提示信息。这很自然的就会涉及到多线程的问题。在这个例子中因为每个连接都要创建一 个线程,所以需要对线程进行管理。这里我使用了两个类:Connection(管理具体Socket连接)和SocketListener(管理线程和连 接)。

看看代码吧:

1、Connection:服务端用于接收消息,处理具体的连接

 1 public class Connection
 2     {
 3         Socket _connection;
 4  
 5         public Connection(Socket socket)
 6         {
 7             _connection = socket;
 8         }
 9  
10         public void WaitForSendData()
11         {
12             while (true)
13             {
14                 byte[] bytes = new byte[1024];
15                 string data = "";
16  
17                 //等待接收消息
18                 int bytesRec = this._connection.Receive(bytes);
19  
20                 if (bytesRec == 0)
21                 {
22                     ReceiveText("客户端[" + _connection.RemoteEndPoint.ToString() + "]连接关闭...");
23                     break;
24                 }
25  
26                 data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
27                 ReceiveText("收到消息:" + data);
28  
29                 string sendStr = "服务端已经收到信息!";
30                 byte[] bs = Encoding.UTF8.GetBytes(sendStr);
31                 _connection.Send(bs, bs.Length, 0);
32             }
33         }
34  
35         public delegate void ReceiveTextHandler(string text);
36         public event ReceiveTextHandler ReceiveTextEvent;
37         private void ReceiveText(string text)
38         {
39             if (ReceiveTextEvent != null)
40             {
41                 ReceiveTextEvent(text);
42             }
43         }
44     }
Connection

2、SocketListener:启动服务端Socket监听

 1 public class SocketListener
 2     {
 3         public Hashtable Connection = new Hashtable();
 4  
 5         public void StartListen()
 6         {
 7             try
 8             {
 9                 //端口号、IP地址
10                 int port = 2000;
11                 string host = "127.0.0.1";
12                 IPAddress ip = IPAddress.Parse(host);
13                 IPEndPoint ipe = new IPEndPoint(ip, port);
14  
15                 //创建一个Socket类
16                 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
17                 s.Bind(ipe);//绑定2000端口
18                 s.Listen(0);//开始监听
19  
20                 ReceiveText("启动Socket监听...");
21  
22                 while (true)
23                 {
24                     Socket connectionSocket = s.Accept();//为新建连接创建新的Socket
25  
26                     ReceiveText("客户端[" + connectionSocket.RemoteEndPoint.ToString() + "]连接已建立...");
27  
28                     Connection gpsCn = new Connection(connectionSocket);
29                     gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText);
30  
31                     Connection.Add(connectionSocket.RemoteEndPoint.ToString(), gpsCn);
32  
33                     //在新线程中启动新的socket连接,每个socket等待,并保持连接
34                     Thread thread = new Thread(new ThreadStart(gpsCn.WaitForSendData));
35                     thread.Name = connectionSocket.RemoteEndPoint.ToString();
36                     thread.Start();
37                 }
38             }
39             catch (ArgumentNullException ex1)
40             {
41                 ReceiveText("ArgumentNullException:" + ex1);
42             }
43             catch (SocketException ex2)
44             {
45                 ReceiveText("SocketException:" + ex2);
46             }
47         }
48  
49         public delegate void ReceiveTextHandler(string text);
50         public event ReceiveTextHandler ReceiveTextEvent;
51         private void ReceiveText(string text)
52         {
53             if (ReceiveTextEvent != null)
54             {
55                 ReceiveTextEvent(text);
56             }
57         }
58     }
启动服务端Socket监听

3、服务端主程序

 1  /// <summary>
 2     /// Interaction logic for MainWindow.xaml
 3     /// </summary>
 4     public partial class MainWindow : Window
 5     {
 6         SocketListener listener;
 7         public MainWindow()
 8         {
 9             InitializeComponent();
10  
11             InitServer();
12         }
13  
14         private void InitServer()
15         {
16             System.Timers.Timer t = new System.Timers.Timer(2000);
17             //实例化Timer类,设置间隔时间为5000毫秒;
18             t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);
19             //到达时间的时候执行事件; 
20             t.AutoReset = true;
21             t.Start();
22         }
23  
24         private void CheckListen(object sender, System.Timers.ElapsedEventArgs e)
25         {
26             if (listener != null && listener.Connection != null)
27             {
28                 //label2.Content = listener.Connection.Count.ToString();
29                 ShowText("连接数:" + listener.Connection.Count.ToString());
30             }
31         }
32  
33         private void button1_Click(object sender, RoutedEventArgs e)
34         {
35             Thread th = new Thread(new ThreadStart(SocketListen));
36             th.Start();
37         }
38  
39         private void SocketListen()
40         {
41             listener = new SocketListener();
42             listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText);
43             listener.StartListen();
44         }
45  
46         public delegate void ShowTextHandler(string text);
47         ShowTextHandler setText;
48  
49         private void ShowText(string text)
50         {
51             if (System.Threading.Thread.CurrentThread != txtSocketInfo.Dispatcher.Thread)
52             {
53                 if (setText == null)
54                 {
55                     setText = new ShowTextHandler(ShowText);
56                 }
57                 txtSocketInfo.Dispatcher.BeginInvoke(setText, DispatcherPriority.Normal, new string[] { text });
58             }
59             else
60             {
61                 txtSocketInfo.AppendText(text + "\n");
62             }
63         }
64  
65         private void button2_Click(object sender, RoutedEventArgs e)
66         {
67             ClientWindow client = new ClientWindow();
68             client.Show();
69         }
70     }
服务端主程序

4、客户端:建立连接,发送消息

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    
 
 public partial class ClientWindow : Window
    {
        Socket c;
        public ClientWindow()
        {
            InitializeComponent();
            InitClient();
        }
 
        private void InitClient()
        {
            int port = 2000;
            string host = "127.0.0.1";
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
            c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
 
            ShowText("连接到Socket服务端...");
 
            c.Connect(ipe);//连接到服务器
        }
 
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowText("发送消息到服务端...");
                string sendStr = textBox2.Text;
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                c.Send(bs, bs.Length, 0);
 
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
 
                ShowText("服务器返回信息:" + recvStr);
            }
            catch (ArgumentNullException ex1)
            {
                Console.WriteLine("ArgumentNullException:{0}", ex1);
            }
            catch (SocketException ex2)
            {
                Console.WriteLine("SocketException:{0}", ex2);
            }
        }
 
        private void ShowText(string text)
        {
            txtSockInfo.AppendText(text + "\n");
        }
    }
建立连接,发送消息

这是一个WPF的程序,WPF对多线程访问控件和WinForm的处理方式不太一样。

转自波斯马,原文地址《C#通信之Socket通信的简单例子

posted on 2015-02-13 15:37  波澜不惊super  阅读(4959)  评论(0编辑  收藏  举报

导航