Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8593569
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T00:01:18+00:00 2026-06-12T00:01:18+00:00

I’ve previously used BeginAccept() and BeginRead() , but with Visual Studio 2012 I want

  • 0

I’ve previously used BeginAccept() and BeginRead(), but with Visual Studio 2012 I want to make use of the new asynchronous (async, await) features in my socket server program.

How can I complete the AcceptAsync and ReceiveAsync functions?

using System.Net;
using System.Net.Sockets;

namespace OfficialServer.Core.Server
{
    public abstract class CoreServer
    {
        private const int ListenLength = 500;
        private const int ReceiveTimeOut = 30000;
        private const int SendTimeOut = 30000;
        private readonly Socket _socket;

        protected CoreServer(int port, string ip = "0.0.0.0")
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
            _socket.Listen(ListenLength);
            _socket.ReceiveTimeout = ReceiveTimeOut;
            _socket.SendTimeout = SendTimeOut;
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
        }

        public void Start()
        {    
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T00:01:20+00:00Added an answer on June 12, 2026 at 12:01 am

    …because you’re so determined, I put together a very simple example of how to write an echo server to get you on your way. Anything received gets echoed back to the client. The server will stay running for 60s. Try telnetting to it on localhost port 6666. Take time to understand exactly what’s going on here.

    void Main()
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        TcpListener listener = new TcpListener(IPAddress.Any, 6666);
        try
        {
            listener.Start();
            //just fire and forget. We break from the "forgotten" async loops
            //in AcceptClientsAsync using a CancellationToken from `cts`
            AcceptClientsAsync(listener, cts.Token);
            Thread.Sleep(60000); //block here to hold open the server
        }
        finally
        {
            cts.Cancel();
            listener.Stop();
        }
    }
    
    async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct)
    {
        var clientCounter = 0;
        while (!ct.IsCancellationRequested)
        {
            TcpClient client = await listener.AcceptTcpClientAsync()
                                                .ConfigureAwait(false);
            clientCounter++;
            //once again, just fire and forget, and use the CancellationToken
            //to signal to the "forgotten" async invocation.
            EchoAsync(client, clientCounter, ct);
        }
    
    }
    async Task EchoAsync(TcpClient client,
                         int clientIndex,
                         CancellationToken ct)
    {
        Console.WriteLine("New client ({0}) connected", clientIndex);
        using (client)
        {
            var buf = new byte[4096];
            var stream = client.GetStream();
            while (!ct.IsCancellationRequested)
            {
                //under some circumstances, it's not possible to detect
                //a client disconnecting if there's no data being sent
                //so it's a good idea to give them a timeout to ensure that 
                //we clean them up.
                var timeoutTask = Task.Delay(TimeSpan.FromSeconds(15));
                var amountReadTask = stream.ReadAsync(buf, 0, buf.Length, ct);
                var completedTask = await Task.WhenAny(timeoutTask, amountReadTask)
                                              .ConfigureAwait(false);
                if (completedTask == timeoutTask)
                {
                    var msg = Encoding.ASCII.GetBytes("Client timed out");
                    await stream.WriteAsync(msg, 0, msg.Length);
                    break;
                }
                //now we know that the amountTask is complete so
                //we can ask for its Result without blocking
                var amountRead = amountReadTask.Result;
                if (amountRead == 0) break; //end of stream.
                await stream.WriteAsync(buf, 0, amountRead, ct)
                            .ConfigureAwait(false);
            }
        }
        Console.WriteLine("Client ({0}) disconnected", clientIndex);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want use html5's new tag to play a wav file (currently only supported
I want to count how many characters a certain string has in PHP, but
I have a French site that I want to parse, but am running into
I want to construct a data frame in an Rcpp function, but when I
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I want to show the soap response to UIWebview.. my soap response is, <p><img

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.