C #网络基础编程

网络应用程序的两种设计模式

B/S(Broswer/Server)浏览器/服务器

C/S(clinet/Server)客户端/服务器

引用命名空间:

using sytem.net;

using system.net.sockets;

using system.io;

1 、通信流程

   5b1f9b88198fc59bdc195eb69a3d022102e.jpg

   服务器

   a、      //设置 ip(所要监听和建立连接的IP ) Port //端口
           IPP = new IPEndPoint(IPAddress.Any,65535);

   b、
           //设置 socket IP类型(IPV4(默认) ,IPV6) sokettype 流和包 此为流   协议类型 Tcp/UDP ICMP 等
           socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
   c         //绑定IP 和Port
           socket.Bind(IPP);
           //监听连接
   d    socket.Listen(0);

   e    消息处理发送和接收 

      开启消息监听线程 

       th   th=new th(Receiver);

      public void Receiver(){

         //注意   如果是在UI程序 必须处理线程互斥问题 

          lock(this)

           {   

                    //发生互斥的资源

             }

 

      }

     消息发送

    public  void  Sender(){

 

   }

   f 通信结束 

   关闭掉 IO 流   终止线程   关闭所有socket活动  

  TAcceptMsg.Abort();
   socket.Close();

   客户端

    a  配置要连接的IP和端口(和服务器的端口一样)

           IPP = new IPEndPoint(IPAddress.Parse(txt_addr.Text),int.Parse(txt_port.Text));
      b   //配置socket
                socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                //连接
     c            socket.Connect(IPP);
      d 消息处理

  开启消息监听线程 

       th   th=new th(Receiver);

      public void Receiver(){

         //注意   如果是在UI程序 必须处理线程互斥问题 

          lock(this)

           {   

                    //发生互斥的资源

             }

 

      }

     消息发送

    public  void  Sender(){

 

   }

e  通信结束

    关闭掉 IO 流   终止线程   关闭所有socket活动  

  TAcceptMsg.Abort();
   socket.Close();

2、常用类与其属性方法

3 、常见通信方式

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.IO;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace WinFrm_TcpClient
{
    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;

        }
        //连接状态
        public bool bConnectd = false;
        //监听线程
        public Thread TAcceptMsg = null;
        //用于通信的Ip和Port 
        public IPEndPoint IPP = null;
        //SOcket 通信
        public Socket socket = null;
        //网络数据流
        public NetworkStream nStream=null;
        //读取器
        public TextReader tReader = null;
        //编辑器
        public TextWriter tWriter = null;

        //消息监听发送
        public void AcceptMessage() {

            string tmp;
            while (bConnectd)
            {
                try
                {
                    tmp = tReader.ReadLine();
                    if (tmp.Length != 0)
                    {
                        lock (this)
                        {
                            rich_MessagDialog.AppendText("服务器"+tmp+"\n");
                        }
                    }
                }
                catch {
                    MessageBox.Show("无法连接服务器");
                }
                try
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                }
                catch { }
            }
        


        }

        private void btn_connect_Click(object sender, EventArgs e)
        {
            try
            {
                IPP = new IPEndPoint(IPAddress.Parse(txt_addr.Text),int.Parse(txt_port.Text));
                //配置socket
                socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                //连接
                socket.Connect(IPP);
                if (socket.Connected)
                {
                    nStream = new NetworkStream(socket);
                    tReader = new StreamReader(nStream);
                    tWriter = new StreamWriter(nStream);
                    TAcceptMsg = new Thread(AcceptMessage);
                    bConnectd = true;
                    TAcceptMsg.Start();

                }
            }
            catch {

                MessageBox.Show("无法连接到服务器");
            }
        }

        private void btn_Send_Click(object sender, EventArgs e)
        {
            if (bConnectd)
            {
                try
                {
                    lock (this)
                    rich_MessagDialog.AppendText("客户端" + rich_Sengmsg.Text + "/n");
                    tWriter.WriteLine(rich_Sengmsg.Text);
                    tWriter.Flush();
                    rich_Sengmsg.Text = "";
                }
                catch
                {
                    MessageBox.Show("语与服务器断开");

                }
            }
            else
            {
                MessageBox.Show("未连接服务器,不能通信");
            }
        }

        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                TAcceptMsg.Abort();
                socket.Close();
            }
            catch { }
        }
    }
}

 

服务器

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.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WinFrm_TcpServer
{
    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
            //取消线程异常
            CheckForIllegalCrossThreadCalls = false;
        }
        //服务器连接状态
       private  bool  bConnected=false;
        //监听消息线程
       private Thread tAcceptMsg = null;
        //用于socket通信串口 的 IP 和 Port
       private IPEndPoint IPP = null;
        //Socket通信 
       private Socket socket = null;
        //socket客户端
       private Socket clientsocket = null;
        //网络访问数据流
       private NetworkStream nStream = null;
        //消息读取器
       private TextReader tReader = null;
        //编写器
       private TextWriter tWriter = null;

        //显示消息
       public void AcceptMessag()
       {

           //阻塞连接来自客户端
           clientsocket = socket.Accept();
           if (clientsocket != null)
           {
               bConnected = true;
               lab_state.Text = "客户端连接"+
               clientsocket.RemoteEndPoint.ToString() + "成功建立连接";
           }
           //从客户获取网络数据流  
           nStream=new NetworkStream(clientsocket);
           //读取字节流
           tReader = new StreamReader(nStream);
           //写字节流
           tWriter = new StreamWriter(nStream);

           string tmp;//临时消息缓存
           while (bConnected)
           { 
              //捕获错误
               try
               {
                   tmp = tReader.ReadLine();
                   if (tmp.Length != 0)
                   {
                       //线程互斥处理  
                       lock (this) 
                       {
                           rich_MessageDialog.AppendText( "客户端:"+tmp+"\n");


                       }
                   }
               }
               catch
               {


                   tAcceptMsg.Abort();
                   MessageBox.Show("无法连接到客户端!!");
               
               }
               try
               {
                   //关闭消息发送
                   clientsocket.Shutdown(SocketShutdown.Both);
                   //关闭socket 释放所有资源
                   clientsocket.Close();
                   socket.Shutdown(SocketShutdown.Both);
                   socket.Close();
               }
               catch { }
           }

       
       }

       private void btn_startServer_Click(object sender, EventArgs e)
       {
           //所有ip 和 Port 65535
           IPP = new IPEndPoint(IPAddress.Any,65535);
           //设置 socket IP类型(IPV4(默认) ,IPV6) sokettype 流和包 此为流   协议类型 Tcp/UDP ICMP 等
           socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
           //绑定IP 和Port
           socket.Bind(IPP);
           //监听连接
           socket.Listen(0);

           //开启监听消息线程
           tAcceptMsg = new Thread(AcceptMessag);
           tAcceptMsg.Start();
           btn_startServer.Enabled = false;
       }

       private void btn_Send_Click(object sender, EventArgs e)
       {
           //检测是否有文本
           if (rich_Sendmsg.Text.Length != 0)
           {
               if (bConnected)
               {
                   try {

                       //线程互斥处理
                       lock (this)
                       {

                           rich_MessageDialog.AppendText("服务器"+rich_Sendmsg.Text+"\n");
                          //写入消息
                           tWriter.WriteLine(rich_Sendmsg.Text);
                           //刷新缓冲 
                           tWriter.Flush();
                           rich_Sendmsg.Text = "";
                       }
                   }
                   catch {
                       MessageBox.Show("断开连接无法与客户端通信");
                   }
               
               
               }
           }
           else {

               MessageBox.Show("请输入消息");
           
           }

       }

       private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
       {
           try {
               socket.Close();
               tAcceptMsg.Abort();
           }
           catch { 
           }
       }
    }
}
 

运行环境 : windows 7

开发环境:Microsoft Visual Studio 2010  

源码地址 :https://gitee.com/codemaner/windowscshare_review/tree/master

资源名称 winFrm_tcpclient  winFrm_tcpServer

 

转载于:https://my.oschina.net/u/3768017/blog/1917907

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值