CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2011
    Posts
    19

    TCP server - socket

    I have the source code to listen to a port:

    private Socket _client;
    private Socket _socket;
    private bool _continue = true;

    private void btnConnect_Click(object sender, EventArgs e)
    {
    IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8002);
    _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    _socket.Bind(ip);
    _socket.Listen(10);

    _client = _socket.Accept();
    IPEndPoint clientep = (IPEndPoint)_client.RemoteEndPoint;

    byte[] data;
    while (_continue)
    {
    data = new byte[1024];
    int receivedDataLength = _client.Receive(data);
    // testing - send the same data back to client
    _client.Send(data, receivedDataLength, SocketFlags.None);
    }
    }


    - Do the above source code handle multi-client connection?
    - As this is for testing (it is a WinForm), what should I change if I use that in a Windows service?
    - How do I send the "data" to all connected clients?

    Thanks

  2. #2
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: TCP server - socket

    nope.

    you need to add a loop:

    Code:
    while( serverIsRunning ) {
        _client = _socket.Accept();
        // usually you'll spawn another thread here and process the client in another thread
    }
    where you continuously loop accepting client connections and spin off to process that connection (at least while that server is running).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured