Question C++ convert to VB.Net

stulish

Well-known member
Joined
Jun 6, 2013
Messages
61
Programming Experience
3-5
Hi Guys,

I have been asked to create a module that receives images over a network and some saple code that works, my problem is the sample code is C++ and i have tried to understand it but with not much success.

The code is only 91 lines long with line spaces (see below):

VB.NET:
#include "stdafx.h"
#include <winsock2.h>

struct ImageRxHeader
{
    char            m_token[6];
    unsigned short    m_headerCrc;        // CRC of rest of header
    unsigned short    m_headerVersion;
    unsigned long    m_headerLength;        // octets
    unsigned long    m_dataLength;        // octets
    unsigned long    m_timeSecs;
    unsigned long    m_timeNanoSecs;
    unsigned short    m_diffTime;            // msecs
    unsigned long    m_maxNum;            // packets
    unsigned long    m_actNum;            // packets
    unsigned long    m_streamLength;        // octets
    unsigned char    m_device;
    unsigned char    m_channel;
    unsigned long    m_deviceIp;
    unsigned long    m_devicePort;
    char            m_datatype[16];
    char            m_status[80];
};

DWORD WINAPI clientThread(void *context)
{
    SOCKET s = (SOCKET)context;
    ImageRxHeader vlh;
    int err = recv(s,(char *)&vlh,68,0);

    char *pBuf = new char [vlh.m_dataLength];
    char *pData = pBuf;
    unsigned int bytesLeft = vlh.m_dataLength;
    unsigned int count = 0;
    while ((err = recv(s,pData,bytesLeft,0)) > 0)
    {
        count += err;
        pData += err;
        bytesLeft -= err;
    }

    bool fileWritten = false;
    int index = 0;
    do
    {
        char fileName[80];
        sprintf(fileName,"c:\\test%04d.png",index++);
        unsigned long attrib = GetFileAttributes(fileName);
        if (attrib == INVALID_FILE_ATTRIBUTES)
        {
            FILE *pf = fopen(fileName,"wb");
            fwrite(pBuf,1,vlh.m_dataLength,pf);
            fclose(pf);
            fileWritten = true;
        }
    } while (!fileWritten);
    
    delete pBuf;

    return 0;
}



int _tmain(int argc, _TCHAR* argv[])
{

    WSADATA wsd;
    int err = WSAStartup(MAKEWORD(2,2),&wsd);
    
    SOCKET s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    sockaddr_in sa;
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = 0;
    sa.sin_port = htons(7096);

    bind(s,(const sockaddr *)&sa,sizeof(sa));
    listen(s,5);

    bool keepGoing = true;

    while (keepGoing)
    {
        sockaddr_in clientAddr;
        int cliLen = sizeof(clientAddr);
        SOCKET clientSocket = accept(s,(sockaddr *)&clientAddr,&cliLen);
        DWORD threadId;
        CreateThread(0,0,clientThread,(void *)clientSocket,0,&threadId);
    }
    return 0;
}

I know the IP Address of the Server 172.31.16.17 and the port should be 7096 that it receives the data on. But looking at the C++ code i cant see where it opens a TCP connection with these attributes, i can see the port number, but can not get my head around this.

I have tried creating some small VB apps using TCPCLient and Network Streams but the different ways i have tried all come wont connect.

Is there an easy way to understand how the C++ program is connecting when no IP Has been passed??

Any help is very much appreciated.

Regards

Stu
 
Just want to connect

Just to add a little more below is some basic code, I have tried to just connect and receive the data (i have tried other code just to try to connect):

VB.NET:
Imports System.Net.Sockets
Imports System.Threading.Thread
Imports System.Net
Imports System.Text
Public Class Form1
    Dim ClientSocket As New TcpClient
    Dim ServerStream As NetworkStream
    Dim ServerAddress As String = "172.31.16.17" ' Set the IP address of the server
    Dim PortNumber As Integer = 7096 ' Set the port number used by the server
    Dim OutStream As Byte() 
    Dim ReceivedData As String
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ClientSocket.Connect(ServerAddress, PortNumber)
        Dim inStream(100000) As Byte
        ServerStream = ClientSocket.GetStream()
        ServerStream.Read(inStream, 0, CInt(ClientSocket.ReceiveBufferSize))
        ReceivedData = Encoding.ASCII.GetString(inStream)
        HandleReceivedDate(ReceivedData)
    End Sub
    Private Sub HandleReceivedDate(ByVal msg As String)
        TextBox1.AppendText(msg & vbCrLf)
    End Sub
basic tcp prog.png
The form just has one button and a textbox as shown in the image, but i keep getting the following error:

System.Net.Sockets.SocketException was unhandled
ErrorCode=10061
HResult=-2147467259
Message=No connection could be made because the target machine actively refused it 172.31.16.17:7096
NativeErrorCode=10061
Source=System
StackTrace:
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e) in C:\KH DLL\Try 1\WindowsApplication1\WindowsApplication1\Form1.vb:line 16
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.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(IntPtr 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 Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly 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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
error.png

Thanks

Stu
 
Back
Top