Server using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; namespace SocketTest { class Program { static void Main(string[] args) { Socket serverSk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSk.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8596)); serverSk.Listen(1); SocketAsyncEventArgs AcceptSAE = new SocketAsyncEventArgs(); AcceptSAE.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptSAE_Completed); serverSk.AcceptAsync(AcceptSAE); Console.ReadLine(); } static void AcceptSAE_Completed(object sender, SocketAsyncEventArgs e) { Socket serverSk = sender as Socket; if (e.SocketError == SocketError.Success) { serverSk = e.AcceptSocket; SocketAsyncEventArgs SendSAE = new SocketAsyncEventArgs(); byte[] data = System.Text.Encoding.UTF8.GetBytes("OK,Just Put IT!"); SendSAE.SetBuffer(data, 0, data.Length); SendSAE.Completed += new EventHandler<SocketAsyncEventArgs>(SendSAE_Completed); SocketAsyncEventArgs RecieveSAE = new SocketAsyncEventArgs(); byte[] buffer = new byte[2048]; RecieveSAE.SetBuffer(buffer, 0, buffer.Length); RecieveSAE.Completed += new EventHandler<SocketAsyncEventArgs>(RecieveSAE_Completed); serverSk.ReceiveAsync(RecieveSAE); serverSk.SendAsync(SendSAE); } else Console.WriteLine("接管收集通訊端串連懇求失敗!具體原因請本身調試!"); } static void RecieveSAE_Completed(object sender, SocketAsyncEventArgs e) { Socket sk = sender as Socket; byte[] data = e.Buffer; //重視這裡,如何取接洽關係到通訊端的發送接管的緩衝區中的值。 string msg = System.Text.Encoding.UTF8.GetString(data); Console.WriteLine("Message received: " + msg);
// sk.DisconnectAsync();//你看看 該怎麼做呢? } static void SendSAE_Completed(object sender, SocketAsyncEventArgs e) { Socket sk = sender as Socket; if (e.SocketError == SocketError.Success) { Console.WriteLine("Send complete!"); byte[] data = e.Buffer; //重視這裡,如何取接洽關係到通訊端的發送接管的緩衝區中的值。 string msg = System.Text.Encoding.UTF8.GetString(data); Console.WriteLine("What you sent: " + msg); } } } }
|