Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12838759
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: 嵌入式

2012-08-17 10:34:54

1、TcpListener类

从 TCP 网络客户端侦听连接。

TcpListener 类提供一些简单方法,用于在阻止同步模式下侦听和接受传入连接请求。可使用 或 来连接 TcpListener。可使用 、本地 IP 地址及端口号或者仅使用端口号,来创建 TcpListener。可以将本地 IP 地址指定为 ,将本地端口号指定为 0(如果希望基础服务提供程序为您分配这些值)。如果您选择这样做,可在连接套接字后使用 属性来标识已指定的信息。

方法用来开始侦听传入的连接请求。 将对传入连接进行排队,直至您调用 方法或它已经完成 排队为止。可使用 或 从传入连接请求队列提取连接。这两种方法将阻止。如果要避免阻止,可首先使用 方法来确定队列中是否有可用的连接请求。

调用 方法来关闭 TcpListener。

 

2、TcpClient类

为 TCP 网络服务提供客户端连接。

TcpClient 类提供了一些简单的方法,用于在同步阻止模式下通过网络来连接、发送和接收流数据。

为使 TcpClient 连接并交换数据,使用 TCP 创建的 或 必须侦听是否有传入的连接请求。可以使用下面两种方法之一连接到该侦听器:

    • 创建一个 TcpClient,并调用三个可用的 方法之一。

    • 使用远程主机的主机名和端口号创建 TcpClient。此构造函数将自动尝试一个连接。

注意:

如果要在同步阻止模式下发送无连接数据报,请使用 类。

 

 

image

图1 基本代码执行结构

 

3、源代码

(1)服务器端代码


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Sockets;

  8. namespace TcpListenerDemo
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             TcpListener server = null;
  15.             try
  16.             {
  17.                 /* Set the TcpListener (Server) on port 13000. */
  18.                 Int32 port = 13000;
  19.                 IPAddress localAddr = IPAddress.Parse("127.0.0.1");

  20.                 /* TcpListener server = new TcpListener(port); -----The old API */
  21.                 server = new TcpListener(localAddr, port);

  22.                 /* Start listening for client requests. */
  23.                 server.Start();

  24.                 /* Buffer for reading data */
  25.                 Byte[] bytes = new Byte[256];
  26.                 String data = null;

  27.                 /* Enter the listening loop. */
  28.                 while (true)
  29.                 {
  30.                     Console.Write("I'm Server,Waiting for a connection... ");

  31.                     /*
  32.                     * AcceptTcpClient是一个阻塞型方法,返回用于发送、接收数据的Tcpclient实例。
  33.                     * You could also user server.AcceptSocket() here.
  34.                      */
  35.                     TcpClient client = server.AcceptTcpClient();
  36.                     Console.WriteLine("Connected!");

  37.                     data = null;

  38.                     /* 获取一个stream对象来做reading和writing操作 */
  39.                     NetworkStream stream = client.GetStream();

  40.                     int i;

  41.                     /* Loop to receive all the data sent by the client. */
  42.                     while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
  43.                     {
  44.                         /* Translate data bytes to a ASCII string. */
  45.                         data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
  46.                         Console.WriteLine("Received From Client: {0}\n", data);

  47.                         /* Process the data sent by the client. */
  48.                         data = data.ToUpper();

  49.                         byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

  50.                         /* Send back a response. */
  51.                         stream.Write(msg, 0, msg.Length);
  52.                         Console.WriteLine("Server Sent Back: {0} Server\n", data);
  53.                     }

  54.                     /* Shutdown and end connection */
  55.                     client.Close();
  56.                 }
  57.             }
  58.             catch (SocketException e)
  59.             {
  60.                 Console.WriteLine("SocketException: {0}", e);
  61.             }
  62.             finally
  63.             {
  64.                 /* Stop listening for new clients. */
  65.                 server.Stop();
  66.             }

  67.             Console.WriteLine("\nHit enter to continue...");
  68.             Console.Read();
  69.         }
  70.     }
  71. }

 

(2)客户端代码


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Sockets;

  8. namespace TcpClientDemo
  9. {
  10.     class Program
  11.     {
  12.         static void Connect(String server, String message)
  13.         {
  14.             try
  15.             {
  16.                 /*
  17.                  * Create a TcpClient.
  18.                  * Note, for this client to work you need to have a TcpServer
  19.                  * connected to the same address as specified by the server, port
  20.                  * combination.
  21.                  */
  22.                 Int32 port = 13000;
  23.                 TcpClient client = new TcpClient(server, port);

  24.                 /* Translate the passed message into ASCII and store it as a Byte array. */
  25.                 Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

  26.                 // Get a client stream for reading and writing.
  27.                 // Stream stream = client.GetStream();

  28.                 NetworkStream stream = client.GetStream();

  29.                 /* Send the message to the connected TcpServer. */
  30.                 stream.Write(data, 0, data.Length);

  31.                 Console.WriteLine("Sent: {0}", message);

  32.                 // Receive the TcpServer.response.

  33.                 /* Buffer to store the response bytes. */
  34.                 data = new Byte[256];

  35.                 /* String to store the response ASCII representation. */
  36.                 String responseData = String.Empty;

  37.                 /* Read the first batch of the TcpServer response bytes. */
  38.                 Int32 bytes = stream.Read(data, 0, data.Length);
  39.                 responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
  40.                 Console.WriteLine("Received from Server: {0}", responseData);

  41.                 /* Close everything. */
  42.                 stream.Close();
  43.                 client.Close();
  44.             }
  45.             catch (ArgumentNullException e)
  46.             {
  47.                 Console.WriteLine("ArgumentNullException: {0}", e);
  48.             }
  49.             catch (SocketException e)
  50.             {
  51.                 Console.WriteLine("SocketException: {0}", e);
  52.             }

  53.             Console.WriteLine("\n Press Enter to continue...");
  54.             Console.Read();
  55.         }

  56.         static void Main(string[] args)
  57.         {
  58.             while (true)
  59.             {
  60.                 Connect("127.0.0.1", "This is send from client");
  61.             }
  62.         }
  63.     }
  64. }

 

4、 执行过程

 

image

                                         图4-1 服务器启动

 

image

                                         图4-2 客户端启动

 

image

                                         图4-3 服务器接收到客户端请求

 

 

image

                                         图4-4 双方互发

 

5、工程源码及相关附件


 TcpClientDemo.rar   

 TcpListenerDemo.rar   

 看CSharp tcp通讯类mindmap.rar   




阅读(5459) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~