1、TcpListener类
从 TCP 网络客户端侦听连接。
TcpListener 类提供一些简单方法,用于在阻止同步模式下侦听和接受传入连接请求。可使用 或 来连接 TcpListener。可使用 、本地 IP 地址及端口号或者仅使用端口号,来创建 TcpListener。可以将本地 IP 地址指定为 ,将本地端口号指定为 0(如果希望基础服务提供程序为您分配这些值)。如果您选择这样做,可在连接套接字后使用 属性来标识已指定的信息。
方法用来开始侦听传入的连接请求。 将对传入连接进行排队,直至您调用 方法或它已经完成 排队为止。可使用 或 从传入连接请求队列提取连接。这两种方法将阻止。如果要避免阻止,可首先使用 方法来确定队列中是否有可用的连接请求。
调用 方法来关闭 TcpListener。
2、TcpClient类
为 TCP 网络服务提供客户端连接。
TcpClient 类提供了一些简单的方法,用于在同步阻止模式下通过网络来连接、发送和接收流数据。
为使 TcpClient 连接并交换数据,使用 TCP 创建的 或 必须侦听是否有传入的连接请求。可以使用下面两种方法之一连接到该侦听器:
注意:
如果要在同步阻止模式下发送无连接数据报,请使用 类。
图1 基本代码执行结构
3、源代码
(1)服务器端代码
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- namespace TcpListenerDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- TcpListener server = null;
- try
- {
- /* Set the TcpListener (Server) on port 13000. */
- Int32 port = 13000;
- IPAddress localAddr = IPAddress.Parse("127.0.0.1");
- /* TcpListener server = new TcpListener(port); -----The old API */
- server = new TcpListener(localAddr, port);
- /* Start listening for client requests. */
- server.Start();
- /* Buffer for reading data */
- Byte[] bytes = new Byte[256];
- String data = null;
- /* Enter the listening loop. */
- while (true)
- {
- Console.Write("I'm Server,Waiting for a connection... ");
- /*
- * AcceptTcpClient是一个阻塞型方法,返回用于发送、接收数据的Tcpclient实例。
- * You could also user server.AcceptSocket() here.
- */
- TcpClient client = server.AcceptTcpClient();
- Console.WriteLine("Connected!");
- data = null;
- /* 获取一个stream对象来做reading和writing操作 */
- NetworkStream stream = client.GetStream();
- int i;
- /* Loop to receive all the data sent by the client. */
- while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
- {
- /* Translate data bytes to a ASCII string. */
- data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
- Console.WriteLine("Received From Client: {0}\n", data);
- /* Process the data sent by the client. */
- data = data.ToUpper();
- byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
- /* Send back a response. */
- stream.Write(msg, 0, msg.Length);
- Console.WriteLine("Server Sent Back: {0} Server\n", data);
- }
- /* Shutdown and end connection */
- client.Close();
- }
- }
- catch (SocketException e)
- {
- Console.WriteLine("SocketException: {0}", e);
- }
- finally
- {
- /* Stop listening for new clients. */
- server.Stop();
- }
- Console.WriteLine("\nHit enter to continue...");
- Console.Read();
- }
- }
- }
(2)客户端代码
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- namespace TcpClientDemo
- {
- class Program
- {
- static void Connect(String server, String message)
- {
- try
- {
- /*
- * Create a TcpClient.
- * Note, for this client to work you need to have a TcpServer
- * connected to the same address as specified by the server, port
- * combination.
- */
- Int32 port = 13000;
- TcpClient client = new TcpClient(server, port);
- /* Translate the passed message into ASCII and store it as a Byte array. */
- Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
- // Get a client stream for reading and writing.
- // Stream stream = client.GetStream();
- NetworkStream stream = client.GetStream();
- /* Send the message to the connected TcpServer. */
- stream.Write(data, 0, data.Length);
- Console.WriteLine("Sent: {0}", message);
- // Receive the TcpServer.response.
- /* Buffer to store the response bytes. */
- data = new Byte[256];
- /* String to store the response ASCII representation. */
- String responseData = String.Empty;
- /* Read the first batch of the TcpServer response bytes. */
- Int32 bytes = stream.Read(data, 0, data.Length);
- responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
- Console.WriteLine("Received from Server: {0}", responseData);
- /* Close everything. */
- stream.Close();
- client.Close();
- }
- catch (ArgumentNullException e)
- {
- Console.WriteLine("ArgumentNullException: {0}", e);
- }
- catch (SocketException e)
- {
- Console.WriteLine("SocketException: {0}", e);
- }
- Console.WriteLine("\n Press Enter to continue...");
- Console.Read();
- }
- static void Main(string[] args)
- {
- while (true)
- {
- Connect("127.0.0.1", "This is send from client");
- }
- }
- }
- }
4、 执行过程
图4-1 服务器启动
图4-2 客户端启动
图4-3 服务器接收到客户端请求
图4-4 双方互发
5、工程源码及相关附件
TcpClientDemo.rar
TcpListenerDemo.rar
看CSharp tcp通讯类mindmap.rar
阅读(2826) | 评论(0) | 转发(0) |