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

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

TCP编程 客户端程序一般步骤
1.利用TcpClient的构造函数创建一个TcpClient对象
2.使用Connect方法与服务器建立连接
3.利用TcpClient对象的GetStream对象得到网络流,然后利用该网络流与服务器进行数据传输
4.创建一个线程监听指定的端口,循环接收并处理服务器发送过来的信息。
5.完成工作之后,想服务器发送关闭信息,并关闭与服务器的连接。


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.Net.Sockets; 
using System.Net; 
using System.IO; 
 
namespace TCP 
{ 
  public partial class TcpClientTest : Form 
  { 
    public TcpClientTest() 
    { 
      InitializeComponent(); 
    } 
    private TcpClient tcpClient;//声明 
    private IPAddress iAdress;//IP地址 
    private const int port=58080; //端口  
    private NetworkStream networkStream;//网络流 
    private BinaryReader binayRead;//读取 
    private BinaryWriter binayWrite;//写入 
    private void TcpClient_Load(object sender, EventArgs e) 
    { 
      IPAddress[] ipAddress = Dns.GetHostAddresses("www.baidu.com");//返回主机指定的IP地址 
      iAdress = ipAddress[0]; //初始化IP地址为本地地址 
      IPEndPoint ipoint = new IPEndPoint(iAdress,port);//将网络端点表示为IP和端口号 
      tcpClient = new TcpClient(ipoint);//实例化TcpClient类 
      //最方便 TcpClient tcpClient=new TcpClient("www.baidu.com",port); 
 
      if (tcpClient != null) 
      { 
        networkStream = tcpClient.GetStream();//得到网络流 
        binayRead = new BinaryReader(networkStream); 
        binayWrite = new BinaryWriter(networkStream); 
      } 
    } 
 
    private void ReMessage() 
    { 
      while (true) 
      { 
        try 
        { 
          string rcMsg = binayRead.ReadString();//从网络流中读取数据 
          if (rcMsg != null) 
          { 
            MessageBox.Show(rcMsg); 
          } 
          else 
          { 
            break; 
          } 
        } 
        catch 
        { 
  
        } 
      } 
    } 
  } 
} 
 

注:相关教程知识阅读请移步到c#教程频道。