Library tutorials & articles

Socket Programming in C# - Part 2

Server Side

If you have understood whatever I have described so far, you will easily understand the Server part of the socket application. So far we have been talking about a client making connection to a server and sending and receiving data.

On the Server end, the application has to send and receive data. But in addition to adding and receiving data, server has to allow the clients to make connections by listening at some port. Server does not need to know client I.P. addresses. It really does not care where the client is because its not the server but client who is responsible for making connection. Server's responsibility is to manage client connections.

On the server side there has to be one socket called the Listener socket that listens at a specific port number for client connections. When the client makes a connection, the server needs to accept the connection and then in order for the server to send and receive data from that connected client it needs to talk to that client through the socket that it got when it accepted the connection. The following code illustrates how server listens to the connections and accepts the connection:

public Socket m_socListener;
public void StartListening()
{
    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 );
    }
}

If you look at the above code carefully you will see that its similar to we did in the asynchronous client. First of all the we need to create a listening socket and bind it to a local IP address. Note that we have given Any as the IPAddress (I will explain what it means later), and we have passed the port number as 8221. Next we made a call to Listen function. The 4 is a parameter indicating backlog indicating the maximum length of the queue of pending connections.

Next we made a call to BeginAccept passing it a delegate callback. BeginAccept is a non-blocking method that returns immediately and when a client has made requested a connection, the callback routine is called and you can accept the connection by calling EndAccept. The EndAccept returns a socket object which represents the incoming connection. Here is the code for the callback delegate:

public void OnClientConnect(IAsyncResult asyn)
{
    try
    {
        m_socWorker = m_socListener.EndAccept (asyn);
        WaitForData(m_socWorker);
    }
    catch(ObjectDisposedException)
    {
        System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection: Socket has been closed\n");
    }
    catch(SocketException se)
    {
        MessageBox.Show ( se.Message );
    }
}

Here we accept the connection and call WaitForData which in turn calls BeginReceive for the m_socWorker.

If we want to send data some data to client we use m_socWorker socket for that purpose like this:

Object objData = txtDataTx.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
m_socWorker.Send (byData);

Comments

  1. 02 May 2009 at 04:24
    Multiple Socket Confusion: Q. Where is the entire code for the 'm_asynResult' variable? I tried the following, but still only one client can connect. Never two clients, and never a second client even if the first client disconnects. Help.... public void WaitForData(System.Net.Sockets.Socket soc) { try { if ( pfnWorkerCallBack == null ) { pfnWorkerCallBack = new AsyncCallback (OnDataReceived); } CSocketPacket theSocPkt = new CSocketPacket (); theSocPkt.thisSocket = soc; // now start to listen for any data... //soc.BeginReceive(theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length ,SocketFlags.None,pfnWorkerCallBack,theSocPkt); IAsyncResult m_asyncResult = soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt); } catch(SocketException se) { MessageBox.Show (se.Message ); } }
  2. 02 May 2009 at 04:22
    Multiple Socket Confusion: Q. Where is the entire code for the 'm_asynResult' variable? I tried the following, but still only one client can connect. Never two clients, and never a second client even if the first client disconnects. Help.... public void WaitForData(System.Net.Sockets.Socket soc) { try { if ( pfnWorkerCallBack == null ) { pfnWorkerCallBack = new AsyncCallback (OnDataReceived); } CSocketPacket theSocPkt = new CSocketPacket (); theSocPkt.thisSocket = soc; // now start to listen for any data... //soc.BeginReceive(theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length ,SocketFlags.None,pfnWorkerCallBack,theSocPkt); IAsyncResult m_asyncResult = soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt); } catch(SocketException se) { MessageBox.Show (se.Message ); } }
  3. 24 Apr 2009 at 13:25
    hi , iwant to send data of type int32 on the network by socket c# how i use the method ( send()) . thanks
  4. 21 Jan 2009 at 16:27
    For those who are looking to have multiple clients connecting to the server, you will need to create an arraylist to keep track of all the clients, and add another m_mainSocket.BeginAccept call to the OnClientConnect method.
  5. 12 Dec 2008 at 15:42
    @ the people who have the thread call safe problem. Here is a solution. I only have changed the names of the variables to dutch. But i guess u can figure that one out urself. public void ontvangenData(IAsyncResult asyn) { try { socketpakket theSockId = (socketpakket)asyn.AsyncState; int a = 0; a = theSockId.thisSocket.EndReceive(asyn); char[] chars = new char[a + 1]; System.Text.Decoder b = System.Text.Encoding.UTF8.GetDecoder(); int charLen = b.GetChars(theSockId.dataBuffer, 0, a, chars, 0); System.String data = new System.String(chars); vulText(data); wachtopData(sockwerker); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } } /* Begin thread call safe * * * * */ delegate void setTextCallback(string text); private void vulText(string text) { if (TxtOntvangen.InvokeRequired) { setTextCallback d = new setTextCallback(vulText); this.Invoke(d, new object[] { text }); } else { TxtOntvangen.Text += text; } } /* Einde thread call safe * * * * */
  6. 10 Nov 2008 at 14:57
    Hi, Thanks for your article.Very useful! I haven't been able to think how a continuous communication which server does different actions when client sends a data in, can be provided.Namely,if I don't misunderstand the logic of the program,when a client connects,on server WaitForData function waits for receiving data from client.When server receives,then the asynchronous callback function OnDataReceived is invoked, and the related processes are done. Now, my question is this: After receiving data from client and invoking OnDataReceived function and then sending server's reply, for receiving new data,again it is necessary to call WaitForData fuction, is't it?Then after receiving this new data ,again it is called OnDataReceived function, namely the same processes.Then, how can we provide a continuous data exchange as SendTo-ReceiveFrom consecutively? Thanks in advance.
  7. 16 Oct 2008 at 12:40
    the programme is giving error as cross thread error the application is accessed from the thread other then it is created Within the public method OnDataReceived(IAsyncResult asyn) txtDataRx.Text = txtDataRx.Text + szData; how can I avoid it
  8. 05 Jun 2007 at 05:07
    I was having the same problem until some minutes ago. The code below worked for me. See the bold section. Take a look at the help for Socket.Poll. This will return True only if there is still data to be received in the connected socket. If there's not, it sends the OK message.

    I'll also post the whole code for the Client and Server classes. It may be useful for someone. I spend several hours researching and testing to come up with this...

    I know we are in a C# area, but the code is very easy to translate.






    Private Sub ReceiveCallback(ByVal ar As IAsyncResult)
            Try
                'Retrieve the state object and the client socket
                'from the asynchronous state object.
                Dim state As StateObject = CType(ar.AsyncState, StateObject)
                Dim client As Socket = state.workSocket
                'Read data from the remote device.
                Dim bytesRead As Integer = client.EndReceive(ar)
                If bytesRead > 0 Then
                    'There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
                    'Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)












                    'Check if there is no more data to be received. If not an OK message is sent to the client.
                    If Not client.Poll(1000000, SelectMode.SelectRead) Then
                        Send(client, "OK" & vbCrLf)
                    End If



                Else
                    'All the data has arrived;
                    'Signal that all bytes have been received.
                    receiveDone.Set()
                    InvokeDelegate(state.sb.ToString)
                End If
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try








        End Sub


    ###See the complete solution below:
    _____________________________________________________________________________


    Public Delegate Sub StringReceivedHandlerDelegate(ByVal sRemoteAddress As String)

    Public Class Server

        Private _PortNumber As Integer
        Private DataReceived As StringReceivedHandlerDelegate
        Private listener As Socket

        Sub New(ByVal PortNumber As Integer)
            _PortNumber = PortNumber
        End Sub

        Public Sub StartServer()
            Listen()
        End Sub

        Public Sub StopServer()
            If Not listener Is Nothing Then
                listener.Close()
            End If
        End Sub

        Public Class StateObject
            'Client socket.
            Public workSocket As Socket = Nothing
            'Size of receive buffer.
            Public Const BufferSize As Integer = 8192
            'Receive buffer.
            Public buffer() As Byte = New Byte(BufferSize - 1) {}
            'Received data string.
            Public sb As New StringBuilder
        End Class

        'ManualResetEvent instances signal completion.
        Private Shared connectDone As New ManualResetEvent(False)
        Private Shared sendDone As New ManualResetEvent(False)
        Private Shared receiveDone As New ManualResetEvent(False)

        Private Sub Listen()
            Try
                Dim remoteEP As New IPEndPoint(IPAddress.Any, _PortNumber)
                listener = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                listener.Bind(remoteEP)
                listener.Listen(10)
                listener.BeginAccept(New AsyncCallback(AddressOf ConnectCallback), listener)
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Sub

        Private Sub ConnectCallback(ByVal ar As IAsyncResult)
            Try
                'Retrieve the socket from the state object.
                Dim client As Socket = CType(ar.AsyncState, Socket)
                'Complete the connection.
                client = client.EndAccept(ar)
                Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString())
                'Start Receiving
                Receive(client)
                'Signal that the connection has been made.
                connectDone.Set()
                listener.BeginAccept(New AsyncCallback(AddressOf ConnectCallback), listener)
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Sub

        Private Sub Receive(ByVal client As Socket)
            Try
                'Create the state object.
                Dim state As New StateObject
                state.workSocket = client
                'Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Sub

        Private Sub ReceiveCallback(ByVal ar As IAsyncResult)
            Try
                'Retrieve the state object and the client socket
                'from the asynchronous state object.
                Dim state As StateObject = CType(ar.AsyncState, StateObject)
                Dim client As Socket = state.workSocket
                'Read data from the remote device.
                Dim bytesRead As Integer = client.EndReceive(ar)
                If bytesRead > 0 Then
                    'There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
                    'Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
                    'Check if there is no more data to be received an OK message is sent to the client
                    If Not client.Poll(1000000, SelectMode.SelectRead) Then
                        Send(client, "OK" & vbCrLf)
                    End If
                Else
                    'All the data has arrived;
                    'Signal that all bytes have been received.
                    receiveDone.Set()
                    InvokeDelegate(state.sb.ToString)
                End If
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Sub

        Private Sub Send(ByVal client As Socket, ByVal data As String)
            Try
                'Convert the string data to byte data using ASCII encoding.
                Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
                'Begin sending the data to the remote device.
                client.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), client)
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Sub

        Private Sub SendCallback(ByVal ar As IAsyncResult)
            Try
                'Retrieve the socket from the state object.
                Dim client As Socket = CType(ar.AsyncState, Socket)
                'Complete sending the data to the remote device.
                Dim bytesSent As Integer = client.EndSend(ar)
                Console.WriteLine("Sent {0} bytes to server.", bytesSent)
                'Signal that all bytes have been sent.
                sendDone.Set()
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Sub

        Public Sub SetStringInputHandler(ByVal pMethod As StringReceivedHandlerDelegate)
            Try
                Monitor.Enter(Me)
                If DataReceived Is Nothing Then
                    DataReceived = pMethod
                End If
                Monitor.Exit(Me)
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Sub

        Private Sub InvokeDelegate(ByVal sData As String)
            Try
                DataReceived.Invoke(sData)
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Sub

    End Class

    ____________________________________________________________________________

    Public Class Client

        Private _RemoteHost As String
        Private _RemotePort As Integer
        Private _NetworkStream As NetworkStream
        Dim _TCPClient As TcpClient

        Sub New(ByVal RemoteHost As String, ByVal RemotePort As Integer)
            _RemoteHost = RemoteHost
            _RemotePort = RemotePort
        End Sub

        Public Function SendStringMessage(ByVal Message As String) As String
            Try
                _TCPClient = New TcpClient(_RemoteHost, _RemotePort)
                _NetworkStream = _TCPClient.GetStream()
                '_NetworkStream.WriteTimeout = 10000
                '_NetworkStream.ReadTimeout = 10000
                Dim strResponse As String
                ' Send a string (newline terminated) to the server.
                Dim writer As New System.IO.StreamWriter(_NetworkStream)
                Dim reader As New System.IO.StreamReader(_NetworkStream)
                writer.Write(Message)
                writer.Flush()
                ' Read server response (up to a newline).
                Try
                    strResponse = reader.ReadLine
                Catch ex As Exception
                    strResponse = Nothing
                End Try
                'Close
                writer.Close()
                reader.Close()
                _NetworkStream.Close()
                Return strResponse
            Catch ex As Exception
                Return Nothing
            Finally
                If Not _TCPClient Is Nothing Then
                    _TCPClient.Close()
                    _TCPClient = Nothing
                End If
            End Try
        End Function

    End Class

    Holpe it helped.

    Regards,

    Afas.



























































































































































































































  9. 05 Mar 2007 at 22:14

    Hi

    how can i acknowledege an sending message in  asynchronous  socket program????

    thank you

  10. 27 Feb 2007 at 13:47
    Hello,

    I'm currently working on the both the server and multiple clients with tcp port connections. A port has been opened at server side for listening. Have tried multiple clients connections upto 120 clients. But in certain times, new client connections to the server are failed, but the existing client connection to server side are stil working fine if they're still connected, once they disconnected it, they cant do reconnection.
    Meaning to say that the server side doesnt respond to any new client tcp connection after some times. No specific error message could be found. Do you have any idea on this? Any possibilities for this matter to happen?
    Look forward to your helps. Thanks in advance.

    Cheers.







  11. 21 Feb 2007 at 06:13

    Hi,

    I am new to this forum but I am trying to do exactly what you may have achieved!

    I am trying to connect multiple clients to Server!

    Any Help is appriciated

    AG

  12. 19 Sep 2006 at 05:19
    Nice tutorial on Sockets.
    i've been developing and small network app and this article was very helpfull but i have problems implementing the comunication part, i can connect, receive and send data the problem arise when i try to send several message or objects(via serialization) i found that i get half of the object on the receiving stream, making imposible de deserialization of the object, i don't know if there is a workaround to this or i need to implement tokens in the message to know when to deserialize the object, any help or ideas will be apreciate :)

    also i like to know if there is a way to detect when the remotehost have been disconnected after calling the Socket.BeginReceive() method.

    Sorry for the bad english... Duke
  13. 08 Sep 2006 at 18:33

    The following source code example has some un-safe thread issues.

    Within the public method OnDataReceived(IAsyncResult asyn)

    txtDataRx.Text = txtDataRx.Text + szData;

     

  14. 06 Sep 2006 at 19:47

    hi,
    I try to build a network sniffer in .net framework 2
    and use the socketname.beginReceive(buffer,0,bufferLength,......);
    like raw socket.
    but when I convert the value in the buffer in to string ,there are meaningless staffs.
    Can you help me please..








  15. 07 Feb 2006 at 19:48

    That's Great! But, How can you show me the way to transaction betwen two computer over internet. Especially, in this example! Can you modify code for me to have connection betwen Server and Client over Internet!  :(


    Any more, I have some question want to have any help from you for design : :)


    First: Game Online! Tell me the way to solve this kind of Programming! Server - Client!


    Second: Mobile sendding data between PC and Mobile like Yahoo! Please help me explain my question in detail! :rolleyes:


    Thank you so much for you reading!

  16. 06 Feb 2006 at 12:52

    Hi,


    Iam doing a socket application,facing some problem in that.The issue is the remote host is sending some 10 messages means the client machine is able to capture only 3 to 4 messages.


    i need help terribly.anyone pls help.thanks in advance

  17. 05 Aug 2005 at 16:12


    Hello -


    Using your code - i sometimes come across an issue.


    During the operation of the application, the CPU will
    max out at 99%.


    It stays like that until i end the app (of course)


    I'm not sure where the code block is maxing out at.


    has anyone come across this issue before?


    thanks
    tony

  18. 25 Jan 2005 at 09:58

    In your topic, suppose that I don't want to send charater, but I want to send a binary file. To do this, I read an image from harddisk and then transfer it to binary array.


    When I send the Image binary array, I got a problem. When I know the server finish receiving data ?

  19. 12 Jan 2005 at 22:42
    It turned out the above code worked correctly. I did not supply an end of line character at the end of the query. That caused the socket to wait forever. After adding a EOL character it worked
  20. 12 Jan 2005 at 05:06
    I have also the same problem.
    Do you have any solution?
  21. 26 Dec 2004 at 14:14

    Rekcut-


    You're not very good at the hacking game, mate! We can find you wherever you go.

  22. 30 Nov 2004 at 02:01

    Code:

    private void cmdListenClick(object sender, System.EventArgs e)
           {
               try
               {
                   //create the listening socket...
                   m
    socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);        
                   [B]IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any ,8221);[/B]
                   //bind to local IP Address...
                   msocListener.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 );
               }
           }



    see the red bold line change the

    Code:
    IPAddress.Any
    to the ip address you want

  23. 30 Nov 2004 at 01:54

    When ever you put a socket on the listening state you have to bind that socket with ip address and port number so you can mention the ip address and port before starting the listning process

  24. 30 Nov 2004 at 01:51

    If you want to know that


    1)
    Server sends data and many different clients get that data at same time instead of sending data to each client one by one then use the UDP (Universal datagram protocol) socket instead of TCP socket


    Read or search about "connection less UDP socket connections"


    2) Server receives data from more that one client at the same time then YES! this can be done using threads or multitasking


    3) Server receives data in from different clients from different ports then again Yes! you have to set another socket to listen state in you want server to get data from different port from different users

  25. 19 Aug 2004 at 05:56

    Hi Ken,


    I am having the same problem...
    Did you get it to work?


    Thanks,
    Andre

  26. 26 May 2004 at 07:56

    Hi!
    is it possible that the server manage more accesses in parallel?


    I'm sorry for my bad English

  27. 18 May 2004 at 18:44
    I modified a part of the Form1:
    /* declare a public variable */
    // Recording "cmdListen" button is "Start Listening" or "Stop Listening" so far.
    private bool isListening = false;

    private void cmdListen_Click(object sender, System.EventArgs e) {
       try {
           if ( isListening ) {
               /* closing m_socListener */
               m_socListener.Close();
               cmdListen.Text = "Start Listening";
               btnSend.Enabled = false;
               isListening = false;
           } else {
               /* constructing m_socListener */
               //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.Text = "Stop Listening";
               btnSend.Enabled = true;
               isListening = true;
           }
       } catch(SocketException se) {
           MessageBox.Show ( se.Message );
       }
    }
  28. 15 May 2004 at 17:04
    Can you help me with a telnet connection coding problem? My code can connect and Send, but Receive cannot get the replied messsage.

    My client is a Windows machine. From this I create a socket connection to an IP and a port on a server machine. On the client machine I can manually telnet to the server, Send/Receive message like this:
    Send: telnet IP Port
    Receive: Connected to IP...
    Send: Operation=TotalRecords
    Receive: TotalRecords=1000

    The fact that I can connect/Send/Receive suggests there is no access issue (the server is a linux machine).

    Now here is my socket code. I can Connect and Send ("Operation=TotalRecords"). But Receive keep on waiting but never getting the message "TotalRecords=1000".

    How do I code to receive the reply? Here is my code in C#:

    IPAddress remoteIPAddress = IPAddress.Parse(LinuxIPAddress);
    EndPoint ep = new IPEndPoint(remoteIPAddress, 4321);
    Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    string query="Operation=TotalRecords";
    sock.Connect(ep);
    Encoding ASCII = Encoding.ASCII;
    Byte[] ByteGet = ASCII.GetBytes(query);
    Byte[] RecvBytes = new Byte[256];
    int iTx=sock.Send(ByteGet, ByteGet.Length, 0); //the code worked to this point
    Int32 bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0); //this will wait forever...

    Thank you in advance.

    Ken

  29. 03 May 2004 at 11:57

    Not responses as answers, responses as people asking the same question that I asked.  This is a neat looking solution but it has a logicl problem and will only work with one client, that is not exceptable for an async socket.  Here is a good solution that I have used for an async sockets.
    http://www.theukwebdesigncompany.com/articles/asynchronous-socket-utility-classes.php

  30. 03 May 2004 at 11:07

    Sorry ... where is a response ?? .. thanks

  31. 18 Apr 2004 at 01:25
    I guess that's because in the code, there is:

    IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any ,8221);

  32. 08 Apr 2004 at 18:43

    Sorry I did not look at the complete response list and see that this question was already posted.

  33. 08 Apr 2004 at 18:41

    I tried to running the server app and client app.  Worked great, when I only had one client.  If I run two clients and try to connect to the server I only see messages from the first client to connect.  In fact, if I run one client and connect, then disconnect, and then reconnect, I get no connection refused error, but I do not get any messages comming across to the server.  Is there some socket clean up that is not happening?  I like this scheme of using async sockets but if only one person can connect, well thats a big problem, please enlighten me.

  34. 19 Feb 2004 at 21:55
    Hi,
    I can run the server application successfully with port 8221 but I get an error when I changed the port number to 80, 8100 or others.

    Following is the exception:
    Only one usage of each socket address (protocol/network address/port) is normally permitted.

    Does anyone have any idea of how I can resolve this problem??
  35. 11 Feb 2004 at 02:18

    Managed to figure out the problem with the help of Zane on the microsoft.public.dotnet.languages.csharp newsgroup. Basically it comes down to ping being a UDP packet that does not have a socket connection and so have to use .BeginReceiveFrom rather than BeginReceive.


    Ciao
    Rekcut

  36. 10 Feb 2004 at 02:50

    Hi all,


    I am currently trying to use the client code to simultaneously send icmp packets to several IPs from different threads. i.e. I have the client code as a class and I instantiate a new instance for each different IP. Within the class I implement an asynchronous delegate to run the client code, so that in the mean time I can return to the main  thread and implement a new instance  of the class and send a different icmp packet.


    Thus at any one time I have several instances of the client code running on different threads, waiting for icmp packets to be received on the OnDataReceived callback.


    My problem is that I am finding icmp reply packets from one thread in the receive databuffer of another thread. i.e.
    the CSocketPacket  object returned as a reference in "IAsyncResult asyn" is not coherent. In other words the data in theSockId.dataBuffer does not correspond to the theSockId.thisSocket socket.


    Is this happening because this code is not threadsafe?? or does anyone have any idea of how I can resolve this problem??


    Regards
    Rekkie

  37. 05 Feb 2004 at 01:40
    everything looks fine. i liked the article except one bit. i ran the server and the client and on the client side, i believe it leaks memory. instead of taking the message from the server and putting it in the text box, i ignored it (to avoid the memory from the text stored). i opened the task manager and sent a bunch of messages to the client. the memory for the client kept increaing as long as i sent it more messages. any solutions to this?

    regards,

    tuco
  38. 04 Feb 2004 at 13:43
    I'm new to C#, and due to tome constaints on a project at work, had to learn as much as I could from books in order to test an SDK for a Pocket PC device.  Your sample and walk-through in the article were extremely helpful
  39. 08 Dec 2003 at 17:07
    If I have a system which has several local IP's  is there a way where I can designate which IP the connection is sent from?
  40. 13 Oct 2003 at 10:19

    I get an error when the client closes the connection, and then no new connections can be made. Does anybody have a solution


    Also. Did anybody get it to work with multiple clients?

  41. 13 Oct 2003 at 10:17

    Did any of you get the program to work with multiple clients?


    If so, how did you do it?

  42. 29 Sep 2003 at 10:45
    hi .
    i want to ask if you can send me the program work ( multi client /server )
    can you send to me .

    my email : hamzahwh@yahoo.com
  43. 29 Sep 2003 at 10:44
    hi .
    i want to ask if you can send me the program work ( multi client /server )
    can you send to me .

    my email : hamzahwh@yahoo.com
  44. 29 Sep 2003 at 10:23
    hi .
    i want to ask if you can send me the program work ( multi client /server )
    can you send to me .

    my email : hamzahwh@yahoo.com
  45. 22 Sep 2003 at 05:45

    First, let me thank you for the great article - it has proved really valuable for me in my current project.




    I am currently trying to extend the example to enable transfer of XML-data (or any data). However, I am not sure how to manipulate the recieved data as a complete string to parse using another function.


    Your example revieces a byte at a time and appends this to the content of a text box. Your example uses an "iterative" function to recieve each byte and then calls WaitForData() to wait for the next byte. But to be able to manipulate this data I need to somehow collect it in a string and when the data/command from the client has been received - do something like sending a answer back.


    The setup could be:


    Client sends command: "GetAmountInAccount"
    Server recieves this, checks the  and replyes: "You are broke"


    but how do I detect when the entire command from the client has been received?


    Thanks,




  46. 17 Sep 2003 at 09:59

    Firstly I would just like to say thanks for the great example code. Very helpful. I am now trying to have more than 1 client listen/communicate with the server. I am getting some very strange results though. Can anybody please give me some advice. I have altered the code on the server side to go back to "listening" after the first client connects. This works, but when the second client connects the first client gets kicked out (after a few seconds?) somehow.


    Look forward to any information.


    Thanks
    Jason

  47. 08 Sep 2003 at 06:43
    Hi! I'm testing your code. If you launch several client applications, only the first connect with the server. Which is the problem? Perhaps you don't release socket server / client and the resource keep blocked.

    Grettings!
  48. 01 Jan 1999 at 00:00

    This thread is for discussions of Socket Programming in C# - Part 2.

Leave a comment

Sign in or Join us (it's free).

Ashish Dhar
AddThis

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

We'd love to hear what you think! Submit ideas or give us feedback