Send a suggestion!

We're building a brand new version of the site, and we'd love to hear your ideas

Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

[3997] Socket Programming in C# - Part 2

Last post 06-05-2007 5:07 AM by afas. 40 replies.
Page 3 of 3 (41 items) < Previous 1 2 3
Sort Posts: Previous Next
  • 01-25-2005 9:58 AM In reply to

    • hoctap
    • Not Ranked
    • Joined on 01-25-2005
    • New Member
    • Points 10

    Problem with receive data

    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 ?
    • Post Points: 0
  • Advertisement

    • Red Gate Software

    Advertisement

    Want to boost your .NET application performance?

    Some developers always seem to write efficient and lightening-fast code. What is their secret? It’s ANTS Profiler. “We improved the performance of the application up to 10 times” Dan Ports, Intrigma.

    Try it for yourself now.

  • 08-05-2005 4:12 PM In reply to

    CPU maxxed out


    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
    • Post Points: 0
  • 02-06-2006 12:52 PM In reply to

    • Suganya
    • Not Ranked
    • Joined on 02-06-2006
    • New Member
    • Points 10

    Socket error -- pls help

    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
    • Post Points: 0
  • 02-07-2006 7:48 PM In reply to

    help me the way connection over internet

    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!
    • Post Points: 0
  • 09-06-2006 7:47 PM In reply to

    • erhan
    • Not Ranked
    • Joined on 09-06-2006
    • New Member
    • Points 5

    Re: [3997] Socket Programming in C# - Part 2

    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..








    • Post Points: 5
  • 09-08-2006 6:33 PM In reply to

    • gcadmes
    • Not Ranked
    • Joined on 04-27-2006
    • United States
    • New Member
    • Points 5

    Re: [3997] Socket Programming in C# - Part 2

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

    Within the public method OnDataReceived(IAsyncResult asyn)

    txtDataRx.Text = txtDataRx.Text + szData;

     

    • Post Points: 5
  • 09-19-2006 5:19 AM In reply to

    • Duke_tj
    • Not Ranked
    • Joined on 09-19-2006
    • New Member
    • Points 5

    Re: [3997] Socket Programming in C# - Part 2

    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
    • Post Points: 5
  • 02-21-2007 6:13 AM In reply to

    • AG
    • Not Ranked
    • Joined on 02-21-2007
    • New Member
    • Points 10

    Re: Problems with multiple clients connecting

    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

    • Post Points: 10
  • 02-27-2007 1:47 PM In reply to

    Re: Problems with multiple clients connecting

    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.







    • Post Points: 5
  • 03-05-2007 10:14 PM In reply to

    • hager
    • Not Ranked
    • Joined on 03-05-2007
    • New Member
    • Points 10

    Re: [3997] Socket Programming in C# - Part 2

    Hi

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

    thank you

    • Post Points: 10
  • 06-05-2007 5:07 AM In reply to

    • afas
    • Not Ranked
    • Joined on 06-05-2007
    • Brazil
    • New Member
    • Points 5

    Re: [3997] Socket Programming in C# - Part 2

    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.



























































































































































































































    • Post Points: 5
Page 3 of 3 (41 items) < Previous 1 2 3