socket数据传输

  1. //同步socket客户端
  2. using System; 
  3. using System.Net; 
  4. using System.Net.Sockets; 
  5. using System.Text; 
  6. public class SynchronousSocketClient 
  7.     public static void StartClient() 
  8.     { 
  9.         byte[] bytes = new byte[1024]; 
  10.         try 
  11.         { 
  12.             IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()) 
  13.             IPAddress ipAddress = ipHostInfo.AddressList[0]; 
  14.             IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000); 
  15.             Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); 
  16.             try 
  17.             { 
  18.                 sender.Connect(remoteEP); 
  19.                 Console.WriteLine("Socket connected to {0}"
  20.                 sender.RemoteEndPoint.ToString()); 
  21.                 byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>"); 
  22.                 int bytesSent = sender.Send(msg); 
  23.                 int bytesRec = sender.Receive(bytes); 
  24.                 Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes,0,bytesRec)); 
  25.                 sender.Shutdown(SocketShutdown.Both); 
  26.                 sender.Close(); 
  27.             } 
  28.             catch (ArgumentNullException ane) 
  29.             { 
  30.                 Console.WriteLine("ArgumentNullException : {0}",ane.ToString()); 
  31.             } 
  32.             catch (SocketException se) 
  33.             { 
  34.                 Console.WriteLine("SocketException : {0}",se.ToString()); 
  35.             }
  36.             catch (Exception e)
  37.             { 
  38.                 Console.WriteLine("Unexpected exception : {0}", e.ToString()); 
  39.             } 
  40.         } 
  41.         catch (Exception e) 
  42.         { 
  43.             Console.WriteLine( e.ToString()); 
  44.         } 
  45.     } 
  46.     public static int Main(String[] args) 
  47.     { 
  48.         StartClient(); 
  49.         return 0; 
  50.     } 
  51. //同步socket监听
  52. using System; 
  53. using System.Net; 
  54. using System.Net.Sockets; 
  55. using System.Text; 
  56. public class SynchronousSocketListener
  57.     public static string data = null
  58.     public static void StartListening() 
  59.     { 
  60.         byte[] bytes = new Byte[1024]; 
  61.          
  62.         IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
  63.         IPAddress ipAddress = ipHostInfo.AddressList[0]; 
  64.         IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 
  65.         Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); 
  66.         try 
  67.         { 
  68.             listener.Bind(localEndPoint); 
  69.             listener.Listen(10); 
  70.              
  71.             while (true
  72.             { 
  73.                 Console.WriteLine("Waiting for a connection..."); 
  74.                 Socket handler = listener.Accept(); 
  75.                 data = null
  76.                 while (true
  77.                 { 
  78.                     bytes = new byte[1024]; 
  79.                     int bytesRec = handler.Receive(bytes); 
  80.                     data += Encoding.ASCII.GetString(bytes,0,bytesRec); 
  81.                     if (data.IndexOf("<EOF>") > -1) 
  82.                     { 
  83.                         break
  84.                     } 
  85.                 } 
  86.                 Console.WriteLine( "Text received : {0}", data); 
  87.                 byte[] msg = Encoding.ASCII.GetBytes(data); 
  88.                 handler.Send(msg); 
  89.                 handler.Shutdown(SocketShutdown.Both); 
  90.                 handler.Close(); 
  91.             } 
  92.         } 
  93.         catch (Exception e) 
  94.         { 
  95.             Console.WriteLine(e.ToString()); 
  96.         } 
  97.         Console.WriteLine("/nPress ENTER to continue..."); 
  98.         Console.Read(); 
  99.     } 
  100.     public static int Main(String[] args) 
  101.     { 
  102.         StartListening(); 
  103.         return 0; 
  104.     } 
  105. //异步socket客户端
  106. using System; 
  107. using System.Net; 
  108. using System.Net.Sockets; 
  109. using System.Threading; 
  110. using System.Text; 
  111.     public class StateObject 
  112.     { 
  113.         public Socket workSocket = null
  114.         public const int BufferSize = 256; 
  115.         public byte[] buffer = new byte[BufferSize]; 
  116.         public StringBuilder sb = new StringBuilder(); 
  117.     } 
  118.     public class AsynchronousClient 
  119.     { 
  120.         private const int port = 11000; 
  121.         private static ManualResetEvent connectDone = new ManualResetEvent(false); 
  122.         private static ManualResetEvent sendDone = new ManualResetEvent(false); 
  123.         private static ManualResetEvent receiveDone = new ManualResetEvent(false); 
  124.          
  125.         private static String response = String.Empty; 
  126.         private static void StartClient() 
  127.         { 
  128.             try 
  129.             { 
  130.                 IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com"); 
  131.                 IPAddress ipAddress = ipHostInfo.AddressList[0]; 
  132.                 IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); 
  133.                 Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
  134.                 client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), client); 
  135.                 connectDone.WaitOne(); 
  136.                 Send(client,"This is a test<EOF>"); 
  137.                 sendDone.WaitOne(); 
  138.                  
  139.                 Receive(client); 
  140.                 receiveDone.WaitOne(); 
  141.                 Console.WriteLine("Response received : {0}", response); 
  142.                 client.Shutdown(SocketShutdown.Both); 
  143.                 client.Close(); 
  144.             } 
  145.             catch (Exception e) 
  146.             { 
  147.                 Console.WriteLine(e.ToString()); 
  148.             } 
  149.         } 
  150.         private static void ConnectCallback(IAsyncResult ar) 
  151.         { 
  152.             try 
  153.             { 
  154.                 Socket client = (Socket) ar.AsyncState; 
  155.                 client.EndConnect(ar); 
  156.                 Console.WriteLine("Socket connected to {0}"
  157.                 client.RemoteEndPoint.ToString()); 
  158.                 connectDone.Set(); 
  159.             } 
  160.             catch (Exception e) 
  161.             { 
  162.                 Console.WriteLine(e.ToString()); 
  163.             } 
  164.         } 
  165.         private static void Receive(Socket client) 
  166.         { 
  167.             try 
  168.             { 
  169.                 StateObject state = new StateObject(); 
  170.                 state.workSocket = client; 
  171.                 client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); 
  172.             } 
  173.             catch (Exception e) 
  174.             { 
  175.                 Console.WriteLine(e.ToString()); 
  176.             } 
  177.         } 
  178.         private static void ReceiveCallback( IAsyncResult ar ) 
  179.         { 
  180.             try 
  181.             { 
  182.                 StateObject state = (StateObject) ar.AsyncState; 
  183.                 Socket client = state.workSocket; 
  184.                 int bytesRead = client.EndReceive(ar); 
  185.                 if (bytesRead > 0) 
  186.                 { 
  187.                     state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead)); 
  188.                     client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, new AsyncCallback(ReceiveCallback), state); 
  189.                 } 
  190.                 else 
  191.                 { 
  192.                     if (state.sb.Length > 1) 
  193.                     { 
  194.                         response = state.sb.ToString(); 
  195.                     } 
  196.                     receiveDone.Set(); 
  197.                 } 
  198.             } 
  199.             catch (Exception e)
  200.             { 
  201.                 Console.WriteLine(e.ToString()); 
  202.             } 
  203.         } 
  204.         private static void Send(Socket client, String data) 
  205.         { 
  206.             byte[] byteData = Encoding.ASCII.GetBytes(data); 
  207.             client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); 
  208.         } 
  209.         private static void SendCallback(IAsyncResult ar) 
  210.         { 
  211.             try 
  212.             { 
  213.                 Socket client = (Socket) ar.AsyncState;          
  214.                 int bytesSent = client.EndSend(ar); 
  215.                 Console.WriteLine("Sent {0} bytes to server.", bytesSent); 
  216.                 sendDone.Set(); 
  217.             } 
  218.             catch (Exception e) 
  219.             { 
  220.                 Console.WriteLine(e.ToString()); 
  221.             } 
  222.         } 
  223.         public static int Main(String[] args) 
  224.         { 
  225.             StartClient(); 
  226.             return 0; 
  227.         } 
  228.     } 
  229. //异步socket监听
  230. using System; 
  231. using System.Net; 
  232. using System.Net.Sockets; 
  233. using System.Text; 
  234. using System.Threading; 
  235. public class StateObject 
  236.     public Socket workSocket = null
  237.     public const int BufferSize = 1024; 
  238.     public byte[] buffer = new byte[BufferSize]; 
  239.     public StringBuilder sb = new StringBuilder(); 
  240. public class AsynchronousSocketListener 
  241.     public static ManualResetEvent allDone = new ManualResetEvent(false); 
  242.     public AsynchronousSocketListener() 
  243.     { 
  244.     } 
  245.     public static void StartListening() 
  246.     {  
  247.         byte[] bytes = new Byte[1024]; 
  248.         IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
  249.         IPAddress ipAddress = ipHostInfo.AddressList[0]; 
  250.         IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 
  251.         Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); 
  252.         try 
  253.         { 
  254.             listener.Bind(localEndPoint); 
  255.             listener.Listen(100); 
  256.             while (true
  257.             { 
  258.                 allDone.Reset(); 
  259.                 Console.WriteLine("Waiting for a connection..."); 
  260.                 listener.BeginAccept( new AsyncCallback(AcceptCallback), listener ); 
  261.                 allDone.WaitOne(); 
  262.             } 
  263.         } 
  264.         catch (Exception e) 
  265.         { 
  266.             Console.WriteLine(e.ToString()); 
  267.         } 
  268.         Console.WriteLine("/nPress ENTER to continue..."); 
  269.         Console.Read(); 
  270.     } 
  271.     public static void AcceptCallback(IAsyncResult ar) 
  272.     { 
  273.         allDone.Set(); 
  274.         Socket listener = (Socket) ar.AsyncState; 
  275.         Socket handler = listener.EndAccept(ar); 
  276.         StateObject state = new StateObject(); 
  277.         state.workSocket = handler; 
  278.         handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); 
  279.     } 
  280.     public static void ReadCallback(IAsyncResult ar) 
  281.     { 
  282.         String content = String.Empty; 
  283.         StateObject state = (StateObject) ar.AsyncState; 
  284.         Socket handler = state.workSocket; 
  285.         int bytesRead = handler.EndReceive(ar); 
  286.         if (bytesRead > 0) 
  287.         { 
  288.             state.sb.Append(Encoding.ASCII.GetString( state.buffer,0,bytesRead));  
  289.             content = state.sb.ToString(); 
  290.             if (content.IndexOf("<EOF>") > -1) 
  291.             { 
  292.                 Console.WriteLine("Read {0} bytes from socket. /n Data : {1}", content.Length, content ); 
  293.                 Send(handler, content); 
  294.             } 
  295.             else 
  296.             { 
  297.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); 
  298.             } 
  299.         } 
  300.     } 
  301.     private static void Send(Socket handler, String data) 
  302.     { 
  303.         byte[] byteData = Encoding.ASCII.GetBytes(data); 
  304.         handler.BeginSend(byteData, 0, byteData.Length, 0, 
  305.         new AsyncCallback(SendCallback), handler); 
  306.     } 
  307.     private static void SendCallback(IAsyncResult ar)
  308.     { 
  309.         try 
  310.         { 
  311.             Socket handler = (Socket) ar.AsyncState; 
  312.             int bytesSent = handler.EndSend(ar); 
  313.             Console.WriteLine("Sent {0} bytes to client.", bytesSent); 
  314.             handler.Shutdown(SocketShutdown.Both); 
  315.             handler.Close(); 
  316.         } 
  317.         catch (Exception e) 
  318.         { 
  319.             Console.WriteLine(e.ToString()); 
  320.         } 
  321.     } 
  322.     public static int Main(String[] args) 
  323.     { 
  324.         StartListening(); 
  325.         return 0; 
  326.     } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值