hi ,

i am doing a project in C#, windows application.
i am using sockets for communication between systems.

now i am facing an error...
its given below..
pls help me to solve this

System.Net.Sockets.SocketException was unhandled
  Message="Only one usage of each socket address (protocol/network address/port) is normally permitted"
  Source="System"
  ErrorCode=10048
  NativeErrorCode=10048
  StackTrace:
       at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.Sockets.Socket.Bind(EndPoint localEP)
       at FTServerCode..ctor() in F:\BK1\projects asp\Lan Chatting sockets\Async_client\Connect.cs:line 1063
       at AsyncClient.Connect..ctor() in F:\BK1\projects asp\Lan Chatting sockets\Async_client\Connect.cs:line 512
       at AsyncClient.HOME.field_Click(Object sender, EventArgs e) in F:\BK1\projects asp\Lan Chatting sockets\Async_client\HOME.cs:line 138
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at DevExpress.XtraEditors.BaseButton.OnClick(EventArgs e)
       at DevExpress.XtraEditors.BaseButton.OnMouseUp(MouseEventArgs e)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at DevExpress.Utils.Controls.ControlBase.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at AsyncClient.LAN_Chatting.Main() in F:\BK1\projects asp\Lan Chatting sockets\Async_client\LAN Chatting.Designer.cs:line 27
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

Please use code tags when pasting data on daniweb. In the case of stack traces you can use plain text:

You need to post the code where you're binding the socket. It looks like you're opening a socket to listen for an inbound connection twice with the same listen port.

There are the files you should post so we can answer your question:

F:\BK1\projects asp\Lan Chatting sockets\Async_client\HOME.cs
F:\BK1\projects asp\Lan Chatting sockets\Async_client\Connect.cs

Developer express controls rock! ;)

F:\BK1\projects asp\Lan Chatting sockets\Async_client\HOME.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace AsyncClient
{
    public partial class HOME : DevExpress.XtraEditors.XtraForm
    {
        public string username;
        public HOME()
        {
           
            InitializeComponent();
            
        }
        

        
        private void label1_Click(object sender, EventArgs e)
        {
            
            this.Close();
            LAN_Chatting frm = new LAN_Chatting();
            frm.Show();
        }

        private void HOME_Load(object sender, EventArgs e)
        {
            //label3.Text = username;
        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Connect frm = new Connect();
            frm.Show();
        }

        private void fileRecievingPathToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void viewFriendsListToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void editFriendsListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FriendList frm = new FriendList();
            frm.Show();
        }

        
    }
}

F:\BK1\projects asp\Lan Chatting sockets\Async_client\Connect.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.IO;


namespace AsyncClient
{
    public partial class Connect : System.Windows.Forms.Form
    {
        public string client_ip;
        byte[] m_DataBuffer = new byte[10];
        IAsyncResult m_asynResult;
        public AsyncCallback pfnCallBack;
        public Socket m_socClient;


        public AsyncCallback pfnWorkerCallBack;
        public Socket m_socListener;
        public Socket m_socWorker;
       
        private System.Windows.Forms.TextBox txtPort;
        private System.Windows.Forms.Button cmdSend;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.Button cmdConnect;
        private System.Windows.Forms.Button cmdClose;
        private System.Windows.Forms.TextBox txtIPAddr;
        
        int port;
        string file;
       
        public Connect()
        {
            InitializeComponent();
            FTServerCode.receivedPath = "";
        }
         private void EnableCommands(bool abEnableConnect)
        {
            
            button1.Enabled = abEnableConnect;
        }
        public class CSocketPacket
        {
            public System.Net.Sockets.Socket thisSocket;
            public byte[] dataBuffer = new byte[1];
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                
                EnableCommands(true);
                //create the socket instance...
                m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // get the remote IP address...
                client_ip = comboBox1.SelectedItem.ToString();
                string myIP = System.Net.Dns.GetHostByName(comboBox1.SelectedItem.ToString()).AddressList[0].ToString();
                IPAddress ip = IPAddress.Parse(myIP);
         /*       if (comboBox2.SelectedItem.Equals("Default"))
                {
                    port = 8221;
                }
                else
                    MessageBox.Show("Port not available");*/
                int iPortNo = 8444;
                //create the end point 
                IPEndPoint ipEnd = new IPEndPoint(ip.Address, iPortNo);
                //connect to the remote host...
                m_socClient.Connect(ipEnd);
                EnableCommands(false);
                //watch for data ( asynchronously )...
                //groupBox1.Visible = false;
                groupBox2.Visible = true;
                WaitForData();
                //Chat_Window frm = new Chat_Window();
                //frm.Show();
            }
            catch (SocketException se)
            {
               
                MessageBox.Show(se.Message);
                EnableCommands(true);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (m_socClient != null)
            {
                //m_socClient.Shutdown (SocketShutdown.Send);
                m_socClient.Close();
                m_socClient = null;
                EnableCommands(true);
                MessageBox.Show("All Connections are Disconnected");
                
            }
        }
       
        
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                Object objData = textBox2.Text;

                textBox1.Text = textBox1.Text + "\r\nME-> " + textBox2.Text + "\r\n";
                textBox2.Text = "";
                
                
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                m_socClient.Send(byData);

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //File
        private void button5_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "Open your File";
            //openFileDialog1.ShowDialog();
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                file = openFileDialog1.FileName.ToString();
            }


            try
            {
                IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
                IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);

                /* Make IP end point same as Server. */
                Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                /* Make a client socket to send data to server. */

                string filePath = "";
                /* File reading operation. */
                file = file.Replace("\\", "/");
                while (file.IndexOf("/") > -1)
                {
                    filePath += file.Substring(0, file.IndexOf("/") + 1);
                    file = file.Substring(file.IndexOf("/") + 1);
                }


                byte[] fileByte = Encoding.ASCII.GetBytes(file);
                if (fileByte.Length > 850 * 1024)
                {
                    //curMsg = "File size is more than 850kb, please try with small file.";
                    return;
                }

                // curMsg = "Buffering ...";
                byte[] fileData = File.ReadAllBytes(filePath + file);

                /* Read & store file byte data in byte array. */
                byte[] clientData = new byte[4 + fileByte.Length + fileData.Length];

                /* clientData will store complete bytes which will store file name length, file name & file data. */
                byte[] fileLen = BitConverter.GetBytes(fileByte.Length);
                /* File name length’s binary data. */
                fileLen.CopyTo(clientData, 0);
                fileByte.CopyTo(clientData, 4);
                fileData.CopyTo(clientData, 4 + fileByte.Length);
                /* copy these bytes to a variable with format line [file name length][file name] [ file content] */
                // curMsg = "Connection to server ...";
                clientSock.Connect(ipEnd);

                //Trying to connection with server. /

           // curMsg = "File sending...";
            clientSock.Send(clientData);
            /* Now connection established, send client data to server. */
                //curMsg = "Disconnecting...";
                clientSock.Close();

                /* Data send complete now close socket. */
                // curMsg = "File transferred.";

            }
            catch (Exception ex)
            {
                //if(ex.Message=="No connection could be made because the target machine actively refused it")
                //  curMsg="File Sending fail. Because server not running." ;
                //else
                //     curMsg = "File Sending fail." + ex.Message;
            }

        }
        /// <summary>
        /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Connect_Load_1(object sender, EventArgs e)
        {
            //create a new NetworkBrowser object, and get the
            //list of network computers it found, and add each
            //entry to the combo box on this form
            
            try
            {
                NetworkBrowser nb = new NetworkBrowser();
                foreach (string pc in nb.getNetworkComputers())
                {


                    // Show the IP

                    //MessageBox.Show(myIP);
                    comboBox1.Items.Add(pc);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred trying to access the network computers", "error",
                                   MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Application.Exit();
            }


            ///////////WaitFor connection
            try
            {
                //create the listening socket...
                m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8444);
                //bind to local IP Address...
                m_socListener.Bind(ipLocal);
                //start listening...
                m_socListener.Listen(4);
                // create the call back for any client connections...
                m_socListener.BeginAccept(new AsyncCallback(OnClientConnect1), null);
                button8.Enabled = false;

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }



            /////Wait File transfer
            try
            {
                if (FTServerCode.receivedPath.Length > 0)
                    backgroundWorker1.RunWorkerAsync();
                else
                    MessageBox.Show("Please select file receiving path");
            }
            catch (SocketException se)
            {
                MessageBox.Show("Connection Error");
            }

            
        }
        /// <summary>
        /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            //HOME frm = new HOME();
            //frm.Show();
            if (m_socClient != null)
            {
                //m_socClient.Shutdown (SocketShutdown.Send);
                m_socClient.Close();
                m_socClient = null;
                //EnableCommands(true);
            }
        }



        /// <summary>
        /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void WaitForData()
        {
            try
            {
                if (pfnCallBack == null)
                {
                    pfnCallBack = new AsyncCallback(OnDataReceived);
                }
                CSocketPacket theSocPkt = new CSocketPacket();
                theSocPkt.thisSocket = m_socClient;
                // now start to listen for any data...
                m_asynResult = m_socClient.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnCallBack, theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
                //end receive...
                int iRx = 0;
                iRx = theSockId.thisSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
                System.String szData = new System.String(chars);
                textBox1.Text =textBox1.Text + "\r\nFag04-> "+szData+"\r\n";
                WaitForData();
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        /*private void cmdListen_Click(object sender, System.EventArgs e)
		{
			try
			{
				//create the listening socket...
				m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);		
				IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any ,8221);
				//bind to local IP Address...
				m_socListener.Bind( ipLocal );
				//start listening...
				m_socListener.Listen (4);
				// create the call back for any client connections...
				m_socListener.BeginAccept(new AsyncCallback( OnClientConnect ),null);
				cmdListen.Enabled = false;

			}
			catch(SocketException se)
			{
				MessageBox.Show ( se.Message );
			}
		}*/
        

      /*  private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                //create the listening socket...
                m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8444);
                //bind to local IP Address...
                m_socListener.Bind(ipLocal);
                //start listening...
                m_socListener.Listen(4);
                // create the call back for any client connections...
                m_socListener.BeginAccept(new AsyncCallback(OnClientConnect1), null);
                button8.Enabled = false;

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        */
        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                Object objData = txtDataTx.Text;
                txtDataRx.Text = txtDataRx.Text + "ME-> " + txtDataTx.TabIndex + "\r\n";
                txtDataTx.Text = "";
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                m_socWorker.Send(byData);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        

        

        

     /*   private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                Object objData = txtDataTx.Text;
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                m_socWorker.Send(byData);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        */
        //server
        public void OnClientConnect1(IAsyncResult asyn)
        {
            try
            {
                m_socWorker = m_socListener.EndAccept(asyn);

                WaitForData1(m_socWorker);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }
        public class CSocketPacket1
        {
            public System.Net.Sockets.Socket thisSocket;
            public byte[] dataBuffer = new byte[1];
        }

        public void WaitForData1(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived1);
                }
                CSocketPacket1 theSocPkt = new CSocketPacket1();
                theSocPkt.thisSocket = soc;
                // now start to listen for any data...
                soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

        public void OnDataReceived1(IAsyncResult asyn)
        {
            try
            {
                CSocketPacket1 theSockId = (CSocketPacket1)asyn.AsyncState;
                //end receive...
                int iRx = 0;
                iRx = theSockId.thisSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
                System.String szData = new System.String(chars);
                textBox1.Text = textBox1.Text + szData;
                WaitForData1(m_socWorker);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        /// <summary>
        /// File Transfer Server
        /// </summary>
        
        /*private void button9_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                FTServerCode.receivedPath = fd.SelectedPath;
            }
        }*/

        /*private void button10_Click(object sender, EventArgs e)
        {
            if (FTServerCode.receivedPath.Length > 0)
                backgroundWorker1.RunWorkerAsync();
            else
                MessageBox.Show("Please select file receiving path");
        }*/
        private void timer1_Tick(object sender, EventArgs e)
        {
            label5.Text = FTServerCode.receivedPath;
            label3.Text = FTServerCode.curMsg;
        }

        FTServerCode obj = new FTServerCode();
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            obj.StartServer();
        }
        private void button11_Click(object sender, EventArgs e)
        {
            FileDialog fDg = new OpenFileDialog();
            if (fDg.ShowDialog() == DialogResult.OK)
            {
                FTClientCode.SendFile(fDg.FileName,client_ip);
            }
        }

        private void recievingPathToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                FTServerCode.receivedPath = fd.SelectedPath;
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            try
            {
                if (FTServerCode.receivedPath.Length > 0)
                    backgroundWorker1.RunWorkerAsync();
                else
                    MessageBox.Show("Please select file receiving path");
            }
            catch (SocketException se)
            {
                MessageBox.Show("Connection Error");
            }

        }

        private void button9_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                FTServerCode.receivedPath = fd.SelectedPath;
                backgroundWorker1.RunWorkerAsync();
            }
        }

        
    }

        class FTServerCode
        {
            IPEndPoint ipEnd;
            Socket sock;
            public FTServerCode()
            {
                ipEnd = new IPEndPoint(IPAddress.Any, 5656);
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                sock.Bind(ipEnd);
            }
            public static string receivedPath;
            public static string curMsg = "Stopped";
            public void StartServer()
            {
                try
                {
                    curMsg = "Starting...";
                    sock.Listen(100);

                    curMsg = "Running and waiting to receive file.";
                    Socket clientSock = sock.Accept();

                    byte[] clientData = new byte[1024 * 5000];

                    int receivedBytesLen = clientSock.Receive(clientData);
                    curMsg = "Receiving data...";

                    int fileNameLen = BitConverter.ToInt32(clientData, 0);
                    string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);

                    BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + "/" + fileName, FileMode.Append)); ;
                    bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);

                    curMsg = "Saving file...";

                    bWrite.Close();
                    clientSock.Close();
                    curMsg = "Reeived & Saved file; Server Stopped.";
                }
                catch (Exception ex)
                {
                    curMsg = "File Receving error.";
                }
            }
        }

        
    /// <summary>
    /// File Transfer Client
    /// </summary>
    class FTClientCode
    {
        public static string curMsg = "Idle";
        public static void SendFile(string fileName,string dest_ip)
        {
            try
            {
                string myIP = System.Net.Dns.GetHostByName(dest_ip).AddressList[0].ToString();
                IPAddress ip = IPAddress.Parse(myIP);
                //IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
                IPEndPoint ipEnd = new IPEndPoint(ip.Address, 5656);
                Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);


                string filePath = "";

                fileName = fileName.Replace("\\", "/");
                while (fileName.IndexOf("/") > -1)
                {
                    filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
                    fileName = fileName.Substring(fileName.IndexOf("/") + 1);
                }


                byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
                if (fileNameByte.Length > 850 * 1024)
                {
                    curMsg = "File size is more than 850kb, please try with small file.";
                    return;
                }

                curMsg = "Buffering ...";
                byte[] fileData = File.ReadAllBytes(filePath + fileName);
                byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
                byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

                fileNameLen.CopyTo(clientData, 0);
                fileNameByte.CopyTo(clientData, 4);
                fileData.CopyTo(clientData, 4 + fileNameByte.Length);

                curMsg = "Connection to server ...";
                clientSock.Connect(ipEnd);

                curMsg = "File sending...";
                clientSock.Send(clientData);

                curMsg = "Disconnecting...";
                clientSock.Close();
                curMsg = "File transferred.";

            }
            catch (Exception ex)
            {
                if (ex.Message == "No connection could be made because the target machine actively refused it")
                    curMsg = "File Sending fail. Because server not running.";
                else
                    curMsg = "File Sending fail." + ex.Message;
            }

        }
    }

}

I'm not sure what's causing the error you are receiving. But it looks like you are trying to send the length of the data, the Filename, and the data itself as one object. then trying to pull out the data before you are sure that you have actually received that information.

a good idea would be to first send the length of the file and the filename and then wait for the server to send a message saying its ready to receive the file, then the send the file data. and on the receiving end use a loop that keeps loading data til the read data matches the length sent.

But I am sure sknake is just going to post you a fixed version when he has time anyway. But if you are looking to do it yourself, it helps to start simple, then build on it. That's how I did it. Started with 2 console applications a client and a server, set them up to send and string messages back and fourth the added special commands to send files, then added progress indication, and eventually turned it into a forms application.

hi,
the code i have shown is working in case of two clients. There is no server. The main problem is about socket opening and closing, I think.

In this application i generate buttons corresponding to each system on my LAN from HOME page, ie Connect page is opened for all such systems...
there occurs the error. i cant open a new Connect form if i have once opened it. I tried by closing the Connect form, also closing each socket.
but still the problem remain till the whole application is stopped.
so i have to close whole application whenever i want to connect with another system, which i dnt want.

is there any connection between ports and the exception i am receiving ...

I don't think your posts were complete. Can you upload the project? The reason I say this is:

AsyncClient.HOME.field_Click(Object sender, EventArgs e) in F:\BK1\projects asp\Lan Chatting sockets\Async_client\HOME.cs:line 138

According to the code you pasted HOME.CS is not 138 lines and does not contain a field_Click() method.

Here is what is causing your problem:

ipEnd = new IPEndPoint(IPAddress.Any, 5656);
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                sock.Bind(ipEnd);

The problem is you can only have one instance of one application listening on one port. Your code will fail if someone else already has opened that port for listening, or if you attempt to listen on the same port twice. This is the exception message you received. You should probably explain what you're attempting to do in your project (after you upload it) so we can determine how to solve it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.