Click here to Skip to main content
14,382,525 members
Rate this:
Please Sign up or sign in to vote.
Hello, i try to write a simple asynchronous client/server apps. I know how do it using callback, but i want to invistigate how write client+server using await/async and c# 5.0. Please, help me. It should be simple. Only connect and transfer some bytes.
I know that this can be done using Tasks.
Something like this:
public static Task ConnectAsync(this Socket socket, EndPoint remoteEP)
        {
            return Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, remoteEP, null);
        }

I try to find some examples, but this has no effect.
FYI. without tcplistener and NetworkStream.
Posted
Comments
   
What do you mean, "FYI, without..."? If you want and advise on the solution, how can you require how it should be solved? Do you want just raw sockets? Why?
—SA
123456789igor 1-May-14 9:09am
   
i want to use c#5 and task.factory. If i understand correctly old methods beginXXX endXXX we can "wrap" into task.faktory and then run task. It's a lot easier. But ay this time i don't understand fully how do this
Rate this:
Please Sign up or sign in to vote.

Solution 3

now server can send to client array of byte. But client recieved only 1 iteration. How i can do, that if client connected then it always recieve information from server?
Server:
public ServerSocket(IPAddress ipAddress, int port)
        {
            _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _server.Bind(new IPEndPoint(ipAddress, port));
            _server.Listen(20);
            Console.WriteLine("Wait connection");
            Accept();
        }
        private async Task StartSend(int i)
        {
            try
            {
                CodingImage img = new CodingImage();
                var buffer = img.CodingImages("C:\\image\\file"+i+".bmp");
                Task<int> senTask = SendAsync.AsyncSend(client, buffer, 0, buffer.Length);
            }
            catch(Exception ex)
            {

            }
        }
        private async void Accept()
        {
            for (int i = 0 ;i<14 ;i++ )
            {
                client = await Task.Factory.FromAsync<socket>(_server.BeginAccept, _server.EndAccept, true);
                Console.WriteLine("Connected");
                await StartSend(i);

            }
        }

public static Task<int> AsyncSend(this Socket socket, byte[] buffer, int offset, int count)
        {
            return Task.Factory.FromAsync<int>(
                socket.BeginSend(buffer, offset, count, SocketFlags.None, null, socket),
                socket.EndSend);
        }
</int></int></socket></int>


Client:

private async void Form1_Load(object sender, EventArgs e)
        {
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            ClientSocket cs = new ClientSocket();
            await cs.Connect(ipAddress, 11000);
            //await cs.StartRecieve();
        }
public ClientSocket()
        {
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
        public async Task Connect(IPAddress ipAddress, int port)
        {
            _client.Connect(ipAddress, port);
            if (!_client.Connected)
            {
                Console.WriteLine("Can't connect");
            }else
            Console.WriteLine("Connected");
            int i=0;
            while(i<14)
            {
                await StartRecieve(i);
                i++;
            }
        }
        public async Task StartRecieve(int i)
        {
            try
            {
                var buffer = new byte[999999];
                //Console.WriteLine("Картинка под номером {0} сохранена", i);
                buffer2 = await _client.ReceiveTaskAsync(buffer,0,buffer.Length);
                EncodingImage enc = new EncodingImage();
                enc.EncodingImageForRecievedBuffer(buffer, i);
                Console.WriteLine("Картинка под номером {0} сохранена", i);
            }
            catch (Exception ex)
            {
            }
        }
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Connect success. But how to send bytes, i don't know
private readonly Socket _server;
        public ServerSocket(IPAddress ipAddress, int port)
        {
            _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _server.Bind(new IPEndPoint(ipAddress, port));
            _server.Listen(20);
            Console.WriteLine("Wait connection");
            Accept();
        }
        private async void Accept()
        {
            for (; ; )
            {
                var socket = await Task.Factory.FromAsync<Socket>(_server.BeginAccept, _server.EndAccept, true);
                Console.WriteLine("Connected");
            }
        }
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100