Avik
Avik

Reputation: 2137

Socket Programming

Am trying to create a server application in c#.In the code am using the TcpListener class.


    TcpListener t = new TcpListener(5555);
    t.Start();

However it is providing an error saying: Invalid token '(' in class, struct, or interface member declaration.

Are there additional references required?.
Please help.


namespace WindowsApplication1
{
    public partial class lanmessenger : Form
    {
        [DllImport("user32.dll")]
        static extern bool HideCaret(IntPtr hWnd);

        public lanmessenger()
        {
            InitializeComponent();
        }


        private void textBox1_TextChanged(object sender, EventArgs e)
        {


        }
        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder(this.textBox1.Text);
            sb.AppendLine(this.textBox2.Text);
            this.textBox1.Text = sb.ToString();
            this.textBox2.Text = "\0";
            HideCaret(this.textBox1.Handle);
        }
        private void textBox1_MouseClick(object sender, MouseEventArgs e)
        {
            HideCaret(this.textBox1.Handle);
        }
        StreamWriter streamWriter;
        StreamReader streamReader;
        NetworkStream networkStream;
        TcpListener t = new TcpListener(5555);
        t.Start();




    }
}

This is the full source code upto now. Am unable to find the error.

Upvotes: 1

Views: 643

Answers (5)

patrick
patrick

Reputation: 16979

Are you sure you don't want to use WCF for a server app?

Upvotes: 0

Chris McElligott Park
Chris McElligott Park

Reputation: 3127

Yep, the problem here is just that this code is not inside a method within your class:

t.Start();

That's what's giving you the specific compiler error. You can't make a call to a method within a class itself, that has to be within some other method. The other stuff is fine where it is, syntactically speaking.

Upvotes: 0

Matt Davis
Matt Davis

Reputation: 46052

Providing you have a reference to System.dll in your project and have a using statement for the System.Net.Sockets namespace, there is nothing wrong with the code you've provided.

It looks like you've got one too many '(' lying around somewhere.

Your call to t.Start() has to be in a method of the class. This is wrong:

class lanmessenger
{
    ...
    TcpListener t = new TcpListener(5555);  // ok to initialize like this
    t.Start();  // wrong...put this in a method
}

This is right:

class lanmessenger
{
    TcpListener t = new TcpListener(5555);  // ok to initialize like this

    public lanmessenger
    {
        InitializeComponent();
        t.Start();  // put it here
    }    
}

Upvotes: 1

okutane
okutane

Reputation: 14270

Don't you forget to put that code in some method of some class?

Upvotes: 1

Aamir
Aamir

Reputation: 15576

Works fine for me. You need to add following line in your code.

using System.Net.Sockets;

Upvotes: 2

Related Questions