简体   繁体   中英

socket communication between c# listener and winsock sender dll

The C# app has a background worker thread which starts on a buttonclick.

     private void button1_Click(object sender, EventArgs e)
        {
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            TcpListener serverSocket = new TcpListener(localAddr,7898);
            int requestCount = 0;
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();

            clientSocket = serverSocket.AcceptTcpClient();
            requestCount = 0;

            while ((true))
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[] bytesFrom = new byte[10025];
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    //Console.WriteLine(" >> Data from client - " + dataFromClient);
                    string serverResponse = "Server response " + Convert.ToString(requestCount);
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    //Console.WriteLine(" >> " + serverResponse);
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex.ToString());
                }
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> exit");
            Console.ReadLine();

I also have in the c++ dll that c# references, the following code

     WSADATA WsaDat; 
    if (WSAStartup(MAKEWORD(2,2), &WsaDat) != 0){ 
    cout<<"WSA FAILED\n"; 
    cin.get(); 
    return 0; 
    } 

    SOCKET Socket; 
    Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 
    if (Socket == SOCKET_ERROR){ 
    cout<<"Socket Failed to load\n"; 
    cin.get(); 
    return 0; 
    } 

    SOCKADDR_IN server; 

    server.sin_port=htons (7898); 
    server.sin_family = AF_INET; 

    server.sin_addr.s_addr = INADDR_ANY; 

    if (bind(Socket, (SOCKADDR *)(&server), sizeof (server)) == SOCKET_ERROR)  
    {  
    cout<<"BINDING FAILED\n"; 
    cin.get(); 
    return 0; 
    } 


    char buffer[256];       // Declaring a buffer on the stack

    ZeroMemory(buffer, 256);
    sprintf(buffer,"--------------------- Processing Side (%s) ----------------------       ---  \n", ( side ? "A" : "B" ));
    int nret = send(Socket,

        buffer,

        strlen(buffer), // Note that this specifies the length of the string; not

                // the size of the entire buffer

        0);         // Most often is zero, but see MSDN for other options

If I step into the code, I find that the debugging yellow arrow vanishes at this line

clientSocket = serverSocket.AcceptTcpClient();

The C# GUI comes up and though the button can still be pressed, it does not step into the code again. I got these snippets of code from researching on the internet so perhaps there are errors that I'm unfamiliar with. Can anyone see what is wrong with my efforts? Why does the debugging vanish at the line above and the C# gui come up?

thanks!

thanks for the answers. I did the following but the connect call fails. is this because of the port #? In c# it is 7898. In c++ it is htons(7898) which turns out to be another number.

SOCKADDR_IN server; 

server.sin_port=htons (7898); 
server.sin_family = AF_INET; 

server.sin_addr.s_addr = INADDR_ANY; 

if (bind(Socket, (SOCKADDR *)(&server), sizeof (server)) == SOCKET_ERROR)  
{  
cout<<"BINDING FAILED\n"; 
cin.get(); 
return 0; 
} 
    //----------------------
// Connect to server.
int iResult = connect(Socket, (SOCKADDR *) & server, sizeof (server));
if (iResult == SOCKET_ERROR) {
    wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
    iResult = closesocket(Socket);
    if (iResult == SOCKET_ERROR)
        wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
    WSACleanup();
    return 1;
}

in c#

IPAddress localAddr = IPAddress.Parse("127.0.0.1");

TcpListener serverSocket = new TcpListener(localAddr,7898);

I read the htons documentation and think the port number is okay and not the problem. So wh does it not connect? thanks again!

After the C++ client calls bind it must call connect. Calling send will not work until a successfull connection has been made.

TcpListener.AcceptTcpClient is a blocking operation meaning that no other code will be executed until a client has connected. Therefore you cannot continue debugging since that call will never finish.

The GUI is responsive since you are delegating all the work to a background thread.

First, after the connection error occurs call WSAGetLastError() to get the actual error. That will probably give you some insight. Second, I suspect you are getting a 10014 error because of an invalid size being specified. If you pass sizeof(sockaddr) instead of sizeof(server) you'll probably have more luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM