Thread: C# Socket Listen On Specific Port

  1. #1
    Registered User
    Join Date
    May 2008
    Location
    Australia
    Posts
    230

    C# Socket Listen On Specific Port

    I'm trying to create a socket polling server (well that's the first step anyway - end goal is a reverse proxy server).

    Anyway, I'm fairly useless with C#, but I can't seem to get it to bind a port to a listening socket... It throws an exception every time I run it on the listenSock.bind(endPoint) call:

    Code:
    System.Net.Sockets.SocketException: An invalid argument was supplied
    at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
    at System.Net.Sockets.Socket.Bind(EndPoint localEP)
    at Proxy.Form1..ctor() in Blah:\Form1.cs: line 27
    Code:
    List<Socket> connectedClients = new List<Socket>();
            
            public Form1() {
                InitializeComponent();
    
                IPAddress addr = IPAddress.Parse("127.0.0.1");
                IPEndPoint endPoint = new IPEndPoint(addr, Globals.port);
    
                Socket listenSock =
                    new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    
                while (true) {
                    try {
                        listenSock.Bind(endPoint);
                    }
                    catch (Exception e) {
                        MessageBox.Show(e.ToString());
                    }
                    listenSock.Listen(10);
                    if (listenSock.Poll(0, SelectMode.SelectRead))
                        connectedClients.Add(listenSock.Accept());
    
                    foreach (Socket sock in connectedClients) {
                        if (sock.Poll(0, SelectMode.SelectError))
                            connectedClients.Remove(sock);
                        else if (sock.Poll(0, SelectMode.SelectRead))
                            // placeholder
                            ParserFunction(sock);
                    }
                }
    Can anyone let me know what I'm doing wrong? :/ I've done some Google searches and from the Google hits it appears I'm doing it correctly.

    Thanks!
    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.

  2. #2
    Registered User
    Join Date
    Mar 2009
    Location
    england
    Posts
    209
    Hi, I use the TcpListener class built into .net.

    Before I show any examples of how to use TcpListener, can I first point out a big mistake you've made based on the code you've provided. You are running an endless loop in the form's constructor!! This means user inputs to the GUI will never be processed, indeed the GUI might not even appear at all. In my opinion anything involving an endless loop requires it's own thread.

    Anyway, I have edited your code to demonstrate how you could use the TcpListener object in it's own thread.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Net;
    using System.Threading;
    using System.Net.Sockets;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            private List<Socket> clients = new List<Socket>();
            private Thread listening_thread;
            private TcpListener listener;
    
            public Form1()
            {
                InitializeComponent();
    
                this.listening_thread = new Thread(new ThreadStart(this.ListeningThread));
                this.listening_thread.Start();
            }
    
            private void ListeningThread() // let's listen in another thread instead!!
            {
                int port = 12345; // change as required
    
                this.listener = new TcpListener(IPAddress.Any, port);
    
                try
                {
                    this.listener.Start();
                }
                catch (Exception e) { MessageBox.Show("couldn't bind to port " + port + " -> " + e.Message); return; }
    
                while (true)
                {
                    if (this.listener.Pending())
                        this.clients.Add(this.listener.AcceptSocket()); // won't block because pending was true
    
                    foreach (Socket sock in this.clients)
                        if (sock.Poll(0, SelectMode.SelectError))
                            clients.Remove(sock);
                        else if (sock.Poll(0, SelectMode.SelectRead))
                            ParserFunction(sock);
    
                    Thread.Sleep(30);
                }
            }
    
            private void ParserFunction(Socket sock)
            {
    
            }
        }
    }
    Hope this helps.

  3. #3
    Registered User
    Join Date
    May 2008
    Location
    Australia
    Posts
    230
    Thanks a lot theoobe, appreciated. I'll rework my model around what you've provided.
    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comodo Firewall Vulnerability (Port 0)
    By Mario F. in forum Tech Board
    Replies: 0
    Last Post: 11-11-2009, 08:56 AM
  2. multithread questions
    By kiros88 in forum C Programming
    Replies: 3
    Last Post: 08-14-2009, 06:12 PM
  3. Access is denied when listen on a port
    By George2 in forum C# Programming
    Replies: 1
    Last Post: 05-29-2008, 09:01 AM
  4. socket newbie, losing a few chars from server to client
    By registering in forum Linux Programming
    Replies: 2
    Last Post: 06-07-2003, 11:48 AM
  5. Socket problem
    By k_w_s_t_a_s in forum Linux Programming
    Replies: 2
    Last Post: 05-23-2003, 08:36 AM