Advertisement
Guest User

Untitled

a guest
Feb 1st, 2013
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.53 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9.  
  10. namespace test_client
  11. {
  12.     class Program
  13.     {
  14.         private static Socket socket;
  15.         private static SocketAsyncEventArgs SockAsyncEventArgs; // объект для асинхронной операции на сокете
  16.  
  17.         private static byte[] buff; // буфер обмена
  18.  
  19.         private static void Init()
  20.         {
  21.  
  22.  
  23.             socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  24.             buff = new byte[256];
  25.             SockAsyncEventArgs = new SocketAsyncEventArgs();
  26.             // подписываемся на завершение асинхронного соединения
  27.             SockAsyncEventArgs.Completed += SockAsyncArgs_Completed;
  28.         }
  29.         private static void res()
  30.         {
  31.             try
  32.             {
  33.                 while (true)
  34.                 {
  35.                     if (socket.Available > 0) //если пришли данные
  36.                     {
  37.  
  38.                         //Thread.Sleep(500);
  39.                         ProcessSend(SockAsyncEventArgs); // получаем их
  40.                     }
  41.                 }
  42.             }
  43.             catch (Exception e)
  44.             {
  45.                 Console.WriteLine("res: " + e.Message);
  46.             }
  47.         }
  48.  
  49.         private static void SockAsyncArgs_Completed(object sender, SocketAsyncEventArgs e)
  50.         {
  51.             switch (e.LastOperation)
  52.             {
  53.                 case SocketAsyncOperation.Connect:
  54.                     ProcessConnect(e);
  55.                     break;
  56.                 case SocketAsyncOperation.Receive:
  57.                     ProcessReceive(e);
  58.                     break;
  59.             }
  60.         }
  61.  
  62.         private static void Start_Connect(string address, int port)
  63.         {
  64.             SockAsyncEventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(address), port);
  65.             ConnectAsync(SockAsyncEventArgs);
  66.         }
  67.  
  68.         private static void ConnectAsync(SocketAsyncEventArgs e)
  69.         {
  70.             bool willRaiseEvent = socket.ConnectAsync(e);
  71.             if (!willRaiseEvent)
  72.                 ProcessConnect(e);
  73.         }
  74.  
  75.         private static void ProcessConnect(SocketAsyncEventArgs e)
  76.         {
  77.             if (e.SocketError == SocketError.Success)
  78.             {
  79.                 SockAsyncEventArgs.SetBuffer(buff, 0, buff.Length);
  80.                 res();
  81.             }
  82.             else
  83.                 Console.WriteLine("Lost connection with " + e.RemoteEndPoint.ToString());
  84.  
  85.         }
  86.  
  87.         private static void SendAsync(byte[] data)
  88.         {
  89.             if (socket.Connected && data.Length > 0)
  90.             {
  91.                 SocketAsyncEventArgs e = new SocketAsyncEventArgs();
  92.                 e.SetBuffer(data, 0, data.Length);
  93.                 e.Completed += SockAsyncArgs_Completed;
  94.                 bool willRaiseEvent = socket.SendAsync(e);
  95.                 // Console.WriteLine("bytes sent: "+data.Length);
  96.             }
  97.         }
  98.  
  99.         private static void ProcessSend(SocketAsyncEventArgs e)
  100.         {
  101.             try
  102.             {
  103.                 if (e.SocketError == SocketError.Success)
  104.                 {
  105.                     ReceiveAsync(SockAsyncEventArgs);
  106.                 }
  107.                 else
  108.                 {
  109.                     Console.WriteLine("Not sended");
  110.                 }
  111.             }
  112.             catch (Exception ex)
  113.             {
  114.                 Console.WriteLine("ProcessSend: " + ex.Message);
  115.             }
  116.         }
  117.  
  118.         private static void ReceiveAsync(SocketAsyncEventArgs e)
  119.         {
  120.             try
  121.             {
  122.                 bool willRaiseEvent = socket.ReceiveAsync(e);
  123.                 if (!willRaiseEvent)
  124.                     ProcessReceive(e);
  125.             }
  126.             catch (Exception ex)
  127.             {
  128.                 Console.WriteLine("ReceiveAsync: " + ex.Message);
  129.             }
  130.         }
  131.  
  132.         private static void ProcessReceive(SocketAsyncEventArgs e)
  133.         {
  134.  
  135.             if (e.SocketError == SocketError.Success)
  136.             {
  137.                 try
  138.                 {
  139.                     string s = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred); //получаем идентификатор команды
  140.                     Console.WriteLine(s);
  141.                     //Console.WriteLine("receive bytes: "+e.BytesTransferred);
  142.                 }
  143.                 catch (Exception ex)
  144.                 {
  145.                     Console.WriteLine("ProcessReceive: " + ex.Message);
  146.                 }
  147.  
  148.             }
  149.  
  150.         }
  151.         static int Main(string[] args)
  152.         {
  153.             Init(); //подготовка соединения  с сервером
  154.             Start_Connect("127.0.0.1", 9095); //соединяемся с сервером
  155.             string s = "";
  156.             Console.ReadKey();
  157.             for (int i = 0; i < 20; i++)
  158.             {
  159.                 if (i % 2 > 0)
  160.                 {
  161.                     s = "приветики " + i;
  162.                     SendAsync(Encoding.UTF8.GetBytes(s));
  163.                 }
  164.                 else
  165.                 {
  166.                     s = "ку " + i;
  167.                     SendAsync(Encoding.UTF8.GetBytes(s));
  168.                 }
  169.  
  170.                 Thread.Sleep(250);
  171.             }
  172.             Console.ReadLine();
  173.             return 0;
  174.         }
  175.  
  176.     }
  177.  
  178. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement