百度空间 | 百度首页 
 
查看文章
 
C#.net同步异步SOCKET通讯和多线程总结(8)
2007年10月15日 星期一 15:58

if (textBox2.Text !="")

               {

                    swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据

                    swWriter.Flush();

               }

               else

               {

                    MessageBox.Show("发送信息不能为空!","错误提示!");

               }

          }

          // 清理所有正在使用的资源。

          protected override void Dispose( bool disposing )

          {

               if ( tcpConnect )

               {

                    swWriter.WriteLine ( "STOP" ) ; //发送控制码  

                    swWriter.Flush (); //刷新当前数据流中的数据  

                    nsStream.Close (); //清除资源

                    swWriter.Close ();

               }

               if( disposing )

               {

                    if (components != null)

                    {

                        components.Dispose();

                    }

               }

               base.Dispose( disposing );

          }

异步套接字

BeginAccept

Public IAsyncResult BeginAccept{AsyncCallback callback,object state}

AsyncCallback异步回调方法 object state自定义对象, 返回IasyncResult

Using System;

Namespace mySocket

{

        Public class   Stateobject

{

        Public StateObject(){构造函数逻辑}

}

}à>

Using System;

Using System.Net;

Using System.Net.Sockets;

Using System.Threading;

Using System.Text;

Namespace mysocket

{

        Public Class StateObject

{

        Public Socket worksocket=null;

        Public const int buffersize=1024;

        Public byte[] buffer=new byte[buffersize];

        Public StringBuilder sb=new StringBuilder();

        Public StateObject()

        {}

}

}

实现主机绑定和端口监听:

Private IPAddress myIP=IPAddress.Parse(“127.0.0.1”);

Private IPEndPoint MyServer;

Private Socket mySocket;

Private Socket Handler;

Private Static ManualResetEvent myreset =new ManualResetEvent(false);

Try

{

        IPHostEntry myhost=new IPHostEntry();

        Myhost=dns.gethostbyName(“”);

        String IPString =myhost.Addresslist[0].tostring();

        Myip=IPAddress.Parse(IPString);

}

Catch{MessageBox.Show(“您输入的IP地址格式不正确,重新输入!”);}

Try

{

        MyServer=new IPEndPoint(myIP,Int32.Parse(“Port”));

        Mysocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,Protocol.Tcp);

        Mysocket.Bind(Myserver);

        Mysocket.Listen(50);

        Thread thread=new Thread(new ThreadStart(target));

        Thread.Start();

}

Catch(Exception ee){}

线程target

Private void target()

{

        While(true)

{


类别:一些教程 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu