WinSock (VB6) vs Socket in C #

1

I have a code in VB6 that uses MSWINSCK.OCX to send commands to an equipment, the code is below. But I have to switch to C # and am attempting to use the Sockets class, the problem I'm facing is that the C # program, using Sockets, is not getting the response from the device. In VB6, using MSWINSCK.OCX, it works normal I can send the commands and receive the response.

VB6 code

Private Sub CmdClear_Click()
   TxtRcv.Text = ""
End Sub

Private Sub CmdSend_Click()
   WinSock.RemoteHost = "255.255.255.255" 'ip do equipamento'
   WinSock.SendData TxtSend.Text
End Sub

Private Sub WinSock_DataArrival(ByVal bytesTotal As Long)
   WinSock.GetData s$
   TxtRcv.Text = TxtRcv.Text + s$ + Chr$(13) + Chr$(10)
End Sub

C # code using Sockets

private static void Main(string[] args)
    {
        var host = IPAddress.Parse("192.168.25.200");

        var hostep = new IPEndPoint(host, 3000);

        var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Unspecified);

        try
        {
            sock.Connect(hostep);
        }
        catch (SocketException e)
        {
            Console.WriteLine("Problem connecting to host");
            Console.WriteLine(e.ToString());
            sock.Close();
            return;
        }

        try
        {
            sock.SendTo(Encoding.ASCII.GetBytes("V"), hostep);
        }
        catch (SocketException e)
        {
            Console.WriteLine("Problem sending data");
            Console.WriteLine(e.ToString());
            sock.Close();
            return;
        }

        var receivingUdpClient = new UdpClient(3000);

        try
        {
            var receiveBytes = receivingUdpClient.Receive(ref hostep);

            var returnData = Encoding.ASCII.GetString(receiveBytes);

            Console.WriteLine("Mensagem recebida " + returnData);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        sock.Close();

    }
}
    
asked by anonymous 07.10.2015 / 21:23

1 answer

0

You opened a socket called "sock", made a connection, and sent a string, in this case the letter "V". But from nowhere, you open a "UdpClient" and totally ignore the open socket called "sock" ... I understand you want to send a string and receive another string. Maybe it is better to leave the socket aside and use a better class for this, the TcpClient is better because you can work with Stream which makes it easier to not get straightforward with a byte array. look at an example:

        var host = IPAddress.Parse("192.168.25.200");
        var hostep = new IPEndPoint(host, 3000);

        var tcpClient = new TcpClient(hostep);

        using (var wr = new StreamWriter(tcpClient.GetStream()))
        using (var rd = new StreamReader(tcpClient.GetStream()))
        {
            wr.WriteLine("V");
            wr.Flush();
            var retorno = rd.ReadLine();
        }
    
13.09.2016 / 22:20