100分求C#异步Socket源码.

2024-12-17 02:11:00
推荐回答(2个)
回答1:

TCP协议的接收端using System.Net.Sockets ; //使用到TcpListen类using System.Threading ; //使用到线程 using System.IO ; //使用到StreamReader类int port = 8000; //定义侦听端口号private Thread thThreadRead; //创建线程,用以侦听端口号,接收信息private TcpListener tlTcpListen; //侦听端口号private bool blistener = true; //设定标示位,判断侦听状态private.NetworkStream nsStream; //创建接收的基本数据流 private StreamReader srRead;private System.Windows.Forms.StatusBar statusBar1;private System.Windows.Forms.Button button1;private System.Windows.Forms.ListBox listBox1; //从网络基础数据流中读取数据private TcpClient tcClient ;private void Listen ( ) { try { tlTcpListen = new TcpListener ( port ) ; //以8000端口号来初始化TcpListener实例tlTcpListen.Start ( ) ; //开始监听statusBar1.Text = "正在监听..." ; tcClient = tlTcpListen.AcceptTcpClient ( ) ; //通过TCP连接请求nsStream = tcClient.GetStream ( ) ; //获取用以发送、接收数据的网络基础数据流srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例statusBar1.Text = "已经连接!"; while( blistener ) //循环侦听{ string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据 if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码{ tlTcpListen.Stop(); //关闭侦听nsStream.Close(); //释放资源srRead.Close(); statusBar1.Text = "连接已经关闭!" ; thThreadRead.Abort(); //中止线程return; } string sTime = DateTime.Now.ToShortTimeString ( ) ; //获取接收数据时的时间listBox1.Items.Add ( sTime + " " + sMessage ) ; } } catch ( System.Security.SecurityException ) { MessageBox.Show ( "侦听失败!" , "错误" ) ; } }//开始监听private void button1_Click(object sender, System.EventArgs e){thThreadRead = new Thread ( new ThreadStart ( Listen ) );thThreadRead.Start();//启动线程 button1.Enabled=false; }// 清理所有正在使用的资源。protected override void Dispose( bool disposing ){try { tlTcpListen.Stop(); //关闭侦听 nsStream.Close();srRead.Close();//释放资源 thThreadRead.Abort();//中止线程 } catch{}if( disposing ){if (components != null) {components.Dispose();}}base.Dispose( disposing );}TCP协议的发送端using System.Net.Sockets; //使用到TcpListen类using System.Threading; //使用到线程using System.IO; //使用到StreamWriter类using System.Net; //使用IPAddress类、IPHostEntry类等private StreamWriter swWriter; //用以向网络基础数据流传送数据 private.NetworkStream nsStream; //创建发送数据的网络基础数据流 private TcpClient tcpClient;private System.Windows.Forms.Button button1;private System.Windows.Forms.TextBox textBox1;private System.Windows.Forms.Button button2;private System.Windows.Forms.TextBox textBox2;private System.Windows.Forms.StatusBar statusBar1;private System.Windows.Forms.Label label1;private System.Windows.Forms.Label label2; //通过它实现向远程主机提出TCP连接申请 private bool tcpConnect = false; //定义标识符,用以表示TCP连接是否建立//连接 private void button1_Click(object sender, System.EventArgs e){IPAddress ipRemote ; try { ipRemote = IPAddress.Parse ( textBox1.Text ) ; } catch //判断给定的IP地址的合法性{ MessageBox.Show ( "输入的IP地址不合法!" , "错误提示!" ) ; return ; } IPHostEntry ipHost ; try { ipHost = Dns.Resolve ( textBox1.Text ) ;  } catch //判断IP地址对应主机是否在线{ MessageBox.Show ("远程主机不在线!" , "错误提示!" ) ; return ; } string sHostName = ipHost.HostName ; try { TcpClient tcpClient = new TcpClient(sHostName,8000);//对远程主机的8000端口提出TCP连接申请nsStream = tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据流  swWriter = new StreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例button1.Enabled = false ; button2.Enabled = true ; tcpConnect = true ; statusBar1.Text = "已经连接!" ; } catch { MessageBox.Show ( "无法和远程主机8000端口建立连接!" , "错误提示!" ) ; return ; } }//发送private void button2_Click(object sender, System.EventArgs e){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 );}异步套接字BeginAcceptPublic IAsyncResult BeginAccept{AsyncCallback callback,object state}AsyncCallback异步回调方法 object state自定义对象, 返回IasyncResultUsing 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.Inte.Network,SocketType.Stream,Protocol.Tcp);Mysocket.Bind(Myserver);Mysocket.Listen(50);Thread thread=new Thread(new ThreadStart(target));Thread.Start();}Catch(Exception ee){}线程targetPrivate void target(){While(true){myReset.Reset();mysocket.BeginAccept(new AsyncCallBack(AcceptCallback),mysocket);myReset.WaitOne();}}异步回调方法AcceptCallBackPrivate void AcceptCallback(IAsyncResault ar){myReset.Set();Socket Listener=(Socket)ar.AsyncState;Handler=Listener.EndAccept(ar);StateObject state=new StateObject();State.workSocket=handler;Try{Byte[] byteData=System.Text.Encoding.BigEndianUnicode.GetBytes(“通话!”+”\n\r”);Handler.BeginSend(byuteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);}Catch(Exception ee){MessageBox.Show(ee.Message);}Thread thread=new Thread(new ThreadStart(begreceive));Thread.Start();}

回答2:

留下邮箱发你