C#基于TCP协议的服务器端和客户端通信编程的基础教程

2019-12-30 12:16:26丽君

(7)Stop:关闭监听器
(8)ToString:创建TcpListener对象的字符串表示


2.TcpClient常用的属性与方法
属性:
(1)Client:获取或设置基础套接字
(2)LingerState:获取或设置套接字保持连接的时间
(3)NoDelay:获取或设置一个值,该值在发送或接收缓存冲未满时禁止延迟、
(4)ReceiveBufferSize:获取或设置TCP接收缓存区的大小
(5)ReceiveTimetut:获取或设置套接字接收数据的超时时间
(6)SendBufferSize:获取或设置TCP发送缓存区的大小
(7)SendTimeout:获取或设置套接字发送数据超时时间

方法:
(1)Close:释放TcpClient实例,而不关闭基础连接
(2)Connect:用指定的主机名和端口号将客户端连接到TCP主机
(3)BeginConnect:开始一个远程主机连接的异步请求
(4)GetStream:获取能够发送和接收数据的NetworkStream对象

TCP编程的一般步骤
1.网络通信的最基本的前提就是客户端要先和服务器建立TCP连接
2.服务端要不断的监听客户端是否有连接请求、并且服务端能要识别特定的客户端
3.连接并创建对应的套接字
4.发送数据和接收数据


编写服务器端程序的一般步骤
1.创建一个TcpListener对象,然后调用该对象的Start方法在指定的端口进行监听
2.在单独的线程中,首先循环调用AcceptTcpClient方法接收客户端的连接请求
,从该方法中的返回结果中得到与该客户端对应的TcpClient对象,并利用该对象
的GetStream方法得到NetworkStream。然后再利用该对象得到其他使用更方便的
对象,比如BinaryReader对象、BinaryWrite对象,为进一步与对方通信做准备。
3.每得到一个新的TcpClient对象,就创建一个与客户对应的线程,在线程与对应的
客户进行通信。
4.根据传送信息的情况确定是否关闭与客户连接。


using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Threading; 
using System.Net.Sockets; 
using System.Net; 
using System.IO; 
 
namespace TCP 
{ 
  public partial class TcpListenerTest : Form 
  { 
    public TcpListenerTest() 
    { 
      InitializeComponent(); 
    } 
    //声明 
    private IPAddress localAddress;// IP地址 IPAddress类 在命名空间 using System.Net下 
    private const int port = 58080;//端口 
    private TcpListener tcpListener;//监听套接字 TcpLestener与TcpClient类 在命名空间 using System.Net.Sockets下 
    private TcpClient tcpClient;//服务端与客户端建立连接 
    private NetworkStream newworkStream;//利用NetworkStream对象与远程主机发送数据或接收数据 
    private BinaryReader binaryReader;//读取 BinaryReader与BinaryWriter类在命名空间using System.IO下 
    private BinaryWriter binaryWrite;//写入 
    private void Form1_Load(object sender, EventArgs e) 
    { 
      IPAddress[] listenerIp = Dns.GetHostAddresses("www.baidu.com");//返回主机指定的IP地址 
      localAddress = listenerIp[0]; //初始化IP地址为本地地址 
      tcpListener = new TcpListener(localAddress,port);//创建TcpListener对象 
      tcpListener.Start();//开始监听 
 
      Thread thread = new Thread(AcceptClientConnect);//启动一个线程接收请求 
      thread.Start();//启动线程 
    } 
    //发起请求 
    private void AcceptClientConnect() 
    {  
      while(true) 
      { 
        try 
        { 
          tcpClient = tcpListener.AcceptTcpClient();//从端口接收一个连接,并赋予它TcpClient对象 
          if (tcpClient != null) 
          { 
            newworkStream = tcpClient.GetStream(); 
            binaryReader = new BinaryReader(newworkStream); 
            binaryWrite = new BinaryWriter(newworkStream); 
          } 
 
        } 
        catch 
        { 
          break; 
        } 
      } 
    } 
  } 
}