日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

异步Socket通信总结[转]

發(fā)布時間:2025/3/17 编程问答 11 豆豆
生活随笔 收集整理的這篇文章主要介紹了 异步Socket通信总结[转] 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

服務(wù)端(異步)

using System.Net ;

using System.Net.Sockets ;

using System.IO ;

using System.Text ;

using System.Threading ;

???????? public static ManualResetEvent allDone = new ManualResetEvent(false);?????

???????? private Thread th;

???????? private bool listenerRun = true ;

???????? Socket listener;

???????? private const int MAX_SOCKET=10;

???????? protected override void Dispose( bool disposing )

???????? {

????????????? try

????????????? {

?????????????????? listenerRun = false ;

?????????????????? th.Abort ( ) ;

?????????????????? th = null ;

?????????????????? listener.Close();

????????????? }

????????????? catch { } ???????????? ?

???????? }

//得到本機IP地址

//得到本機IP地址

???????? public static IPAddress GetServerIP()

???????? {

????????????? IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());

????????????? return ieh.AddressList[0];

???????? }

???????? //偵聽方法

???????? private void Listen()

???????? {

????????????? try

????????????? {

?????????????????? int nPort=int.Parse(this.txtLocalPort.Text);

?????????????????? IPAddress ServerIp=GetServerIP();

?????????????????? IPEndPoint iep=new IPEndPoint(ServerIp,nPort);

?????????????????? listener=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

????????????? ?

?????????????????? listener.Bind(iep);

?????????????????? listener.Listen(10);

?????????????????? statusBar1.Panels[0].Text ="端口:"+this.txtLocalPort.Text+"正在監(jiān)聽......";

?????????????????? while(listenerRun)

?????????????????? {??????????????????????????

?????????????????????? allDone.Reset();

?????????????????????? listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);

?????????????????????? allDone.WaitOne();??????????????????

?????????????????? }

????????????? }

????????????? catch (System.Security.SecurityException )

????????????? {

?????????????????? MessageBox.Show ("防火墻安全錯誤!","錯誤",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);

????????????? }

???????? }

???????? //異步回調(diào)函數(shù)

???????? public void AcceptCallback(IAsyncResult ar)

???????? {????????????

????????????? Socket listener = (Socket)ar.AsyncState;

????????????? Socket client=listener.EndAccept(ar) ;

????????????? allDone.Set();

????????????? StateObject state = new StateObject();

????????????? state.workSocket = client;

????????????? //遠端信息

????????????? EndPoint tempRemoteEP = client.RemoteEndPoint;

????????????? IPEndPoint tempRemoteIP = ( IPEndPoint )tempRemoteEP ;

????????????? string rempip=tempRemoteIP.Address.ToString();

????????????? string remoport=tempRemoteIP.Port.ToString();

????????????? IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address ) ;

????????????? string HostName = host.HostName;

????????????? statusBar1.Panels[1].Text ="接受["+HostName+"] "+rempip+":"+remoport+"遠程計算機正確連接!" ;

????????????? this.listboxRemohost.Items.Add("["+HostName+"] "+rempip+":"+remoport);

????????????? client.BeginReceive( state.buffer,0, StateObject.BufferSize, 0,

?????????????????? new AsyncCallback(readCallback), state);?

?????????????????????? ?

???????? }

//異步接收回調(diào)函數(shù)

???????? public void readCallback(IAsyncResult ar)

???????? {

????????????? StateObject state = (StateObject) ar.AsyncState;

????????????? Socket handler = state.workSocket;????????????

????????????? int bytesRead = handler.EndReceive(ar);???????????

????????????? if (bytesRead > 0)

????????????? {

?????????????????? string strmsg=Encoding.ASCII.GetString(state.buffer,0,bytesRead);

?????????????????? state.sb.Append(strmsg);

?????????????????? string content = state.sb.ToString();

?????????????????? ?

?????????????????? //遠端信息

?????????????????? EndPoint tempRemoteEP = handler.RemoteEndPoint;

?????????????????? IPEndPoint tempRemoteIP = ( IPEndPoint )tempRemoteEP ;

?????????????????? string rempip=tempRemoteIP.Address.ToString();

?????????????????? string remoport=tempRemoteIP.Port.ToString();

?????????????????? IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address ) ;

?????????????????? string HostName = host.HostName;

?????????????????? statusBar1.Panels[1].Text ="正在接收["+HostName+"] "+rempip+":"+remoport+"的信息..." ;

?????????????????? string time = DateTime.Now.ToString ();

?????????????????? listboxRecv.Items.Add("("+time+") "+HostName+":");

?????????????????? listboxRecv.Items.Add(strmsg) ;

?????????????????????? ?

?????????????????? if(content.IndexOf("\x99\x99")> -1)

?????????????????? {

?????????????????????? statusBar1.Panels[1].Text ="信息接收完畢!" ;

?????????????????????? //

?????????????????????? //接收到完整的信息

//???????????????????? MessageBox.Show("接收到:"+content);

?????????????????????? string msg=poweryd.CodeParse(content);

?????????????????????? Send(handler,msg);//異步發(fā)送

//???????????????????? Send(content);//用單獨的socket發(fā)送

?????????????????? }

?????????????????? else

?????????????????? {

?????????????????????? handler.BeginReceive(state.buffer,0,StateObject.BufferSize, 0,

??????????????????????????? new AsyncCallback(readCallback), state);

?????????????????? }

????????????? }

???????? }

???????? //異步發(fā)送

???????? private void Send(Socket handler, String data)

???????? {????????????

????????????? byte[] byteData = Encoding.ASCII.GetBytes(data);????????????

????????????? handler.BeginSend(byteData, 0, byteData.Length, 0,

?????????????????? new AsyncCallback(SendCallback), handler);

//??????????? handler.Send(byteData);

???????? }

???????? #region? //用單獨的socket發(fā)送

???????? private void Send(string data)

???????? {????????????

//??????????? string ip=this.txtRemoIP.Text;

//??????????? string port=this.txtRemoport.Text;

//??????????? IPAddress serverIp=IPAddress.Parse(ip);???????????

//??????????? int serverPort=Convert.ToInt32(port);

//??????????? IPEndPoint iep=new IPEndPoint(serverIp,serverPort); ???????????? ?

//??????????? Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

//??????????? socket.Connect(iep);????????????

//??????????? byte[] byteMessage=Encoding.ASCII.GetBytes(data);

//??????????? socket.Send(byteMessage);

//??????????? socket.Shutdown(SocketShutdown.Both);

//??????????? socket.Close();????????????

???????? }

???????? #endregion

//異步發(fā)送回調(diào)函數(shù)

//異步發(fā)送回調(diào)函數(shù)

???????? private static void SendCallback(IAsyncResult ar)

???????? {

????????????? try

????????????? {?????????????????

?????????????????? Socket handler = (Socket) ar.AsyncState;???????????????

?????????????????? int bytesSent = handler.EndSend(ar);

?????????????????? MessageBox.Show("發(fā)送成功!");

?????????????????? handler.Shutdown(SocketShutdown.Both);

?????????????????? handler.Close();

????????????? }

????????????? catch (Exception ex)

????????????? {

?????????????????? MessageBox.Show(ex.ToString());

????????????? }

???????? }

???????? private void btnListen_Click(object sender, System.EventArgs e)

???????? {

????????????? th = new Thread (new ThreadStart(Listen));//以Listen過程來初始化線程實例 ???? ?

????????????? th.Start();//啟動此線程

????????????? this.btnListen.Enabled=false;????????????

???????? }

???????? private void btnClosenet_Click(object sender, System.EventArgs e)

???????? {

????????????? try

????????????? {

?????????????????? listenerRun = false ;

?????????????????? th.Abort ( ) ;

?????????????????? th = null ; ??????????????? ?

?????????????????? listener.Close();

?????????????????? statusBar1.Panels[0].Text= "與客戶端斷開連接!";

?????????????????? statusBar1.Panels[1].Text= "";

????????????? }

????????????? catch

????????????? {

?????????????????? MessageBox.Show("連接尚未建立,斷開無效!","警告");

????????????? } ?????? ?

???????? }

???????? private void btnExit_Click(object sender, System.EventArgs e)

???????? {

????????????? try

????????????? {

?????????????????? listenerRun = false ;

?????????????????? th.Abort ( ) ;

?????????????????? th = null ; ??????????????? ?

?????????????????? listener.Close();

?????????????????? statusBar1.Panels[0].Text= "與客戶端斷開連接!";

?????????????????? statusBar1.Panels[1].Text= "";

????????????? }

????????????? catch(Exception ex)

????????????? {

?????????????????? MessageBox.Show(ex.Message);

????????????? }

????????????? finally

????????????? {

?????????????????? Application.Exit();

????????????? }

???????? }

???? //異步傳遞的狀態(tài)對象

???? public class StateObject

???? {

???????? public Socket workSocket = null;

???????? public const int BufferSize = 1024;

???????? public byte[] buffer = new byte[BufferSize];

???????? public StringBuilder sb = new StringBuilder();

???? }

客戶端(同步發(fā)送并接收):

using System.Net ;

using System.Net.Sockets ;

using System.IO ;

using System.Text ;

using System.Threading ;

???????? Socket socket;

???????? int numbyte=1024;//一次接收到的字節(jié)數(shù)

???????? private void btnConnect_Click(object sender, System.EventArgs e)

???????? {

????????????? try

????????????? {

?????????????????? string ip=this.txtRemoIP.Text;

?????????????????? string port=this.txtRemoport.Text;

???????? ???????? IPAddress serverIp=IPAddress.Parse(ip);???????????

?????????????????? int serverPort=Convert.ToInt32(port);

?????????????????? IPEndPoint iep=new IPEndPoint(serverIp,serverPort);

?????????????????? IPHostEntry host = Dns.GetHostByAddress(iep.Address ) ;

?????????????????? string HostName = host.HostName;

????????????? ?

?????????????????? socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

?????????????????? socket.Connect(iep);

?????????????????? IPEndPoint tempRemoteIP=( IPEndPoint )socket.LocalEndPoint;

?????????????????? statusBar1.Panels[0].Text ="端口:"+tempRemoteIP.Port.ToString()+"正在監(jiān)聽......"; ????? ???? ?

?????????????????? statusBar1.Panels[1].Text ="與遠程計算機["+HostName+"] "+ip+":"+port+"建立連接!" ;

????????????? }

????????????? catch

????????????? {

?????????????????? statusBar1.Panels[0].Text = "無法連接到目標(biāo)計算機!";

????????????? }

????????????? #region

//??????????? byteMessage=Encoding.ASCII.GetBytes(textBox1.Text+"99");

//??????????? socket.Send(byteMessage);

//??????????? byte[] bytes = new byte[1024];

//??????????? socket.Receive(bytes);

//??????????? string str=Encoding.Default.GetString(bytes);

//??????????? MessageBox.Show("接收到:"+str);

//??????????? socket.Shutdown(SocketShutdown.Both);

//??????????? socket.Close();

????????????? #endregion

???????? ?

???????? }

???????? private void btnSend_Click(object sender, System.EventArgs e)

???????? {

????????????? try

????????????? {

?????????????????? statusBar1.Panels[1].Text ="正在發(fā)送信息!" ;

?????????????????? string message=this.txtsend.Text;

?????????????????? SendInfo(message);???????????????????????

????????????? }?????????????????

????????????? catch //異常處理

????????????? {

?????????????????? statusBar1.Panels[0].Text = "無法發(fā)送信息到目標(biāo)計算機!";

????????????? }

???????? }

???????? private void SendInfo(string message)

???????? {

????????????? #region

//??????????? string ip=this.txtip.Text;

//??????????? string port=this.txtport.Text;

//

//??????????? IPAddress serverIp=IPAddress.Parse(ip);???????????

//??????????? int serverPort=Convert.ToInt32(port);

//??????????? IPEndPoint iep=new IPEndPoint(serverIp,serverPort);

//??????????? byte[] byteMessage;

//

//??????????? socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

//??????????? socket.Connect(iep);

????????????? #endregion

????????????? byte[] byteMessage=Encoding.ASCII.GetBytes(message+"\x99\x99");

????????????? socket.Send(byteMessage);

????????????? //遠端信息

????????????? EndPoint tempRemoteEP = socket.RemoteEndPoint;

????????????? IPEndPoint tempRemoteIP = ( IPEndPoint )tempRemoteEP ;

????????????? string rempip=tempRemoteIP.Address.ToString();

????????????? string remoport=tempRemoteIP.Port.ToString();

????????????? IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address ) ;

????????????? string HostName = host.HostName;

????????????? //發(fā)送信息

????????????? string time1 = DateTime.Now.ToString();

????????????? listboxsend.Items.Add ("("+ time1 +") "+ HostName +":");

????????????? listboxsend.Items.Add (message ) ;??

????????????? //發(fā)送完了,直接接收

????????????? StringBuilder sb = new StringBuilder();

????????????? while(true)

????????????? {

?????????????????? statusBar1.Panels[1].Text ="正在等待接收信息..." ;

?????????????????? byte[] bytes = new byte[numbyte];

?????????????????? int recvbytes=socket.Receive(bytes);

?????????????????? string strmsg=Encoding.Default.GetString(bytes);

?????????????????? ?

?????????????????? string time2 = DateTime.Now.ToString();

?????????????????? listboxRecv.Items.Add("("+time2+") "+HostName+":");

?????????????????? listboxRecv.Items.Add (strmsg) ;

?????????????????? ?

?????????????????? sb.Append(strmsg);

?????????????????? if(sb.ToString().IndexOf("\x99\x99")>-1)

?????????????????? {

?????????????????????? break;

?????????????????? }

????????????? }

????????????? statusBar1.Panels[1].Text ="接收信息完畢!" ;

????????????? //

????????????? //代碼解碼

????????????? CodeParse(sb.ToString());

????????????? //

????????????? socket.Shutdown(SocketShutdown.Both);

????????????? socket.Close();

???????? }

?????????http://www.cnblogs.com/saptechnique/archive/2011/12/21/2295862.html

?

總結(jié)

以上是生活随笔為你收集整理的异步Socket通信总结[转]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。