c#listener和winsock发送器dll之间的socket通信

时间:2013-07-09 18:05:49

标签: c# c++

C#app有一个后台工作线程,它从按钮开始。

     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();

我还在c ++ dll中有c#引用,以下代码

     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

如果我进入代码,我发现调试黄色箭头在此行消失

clientSocket = serverSocket.AcceptTcpClient();

C#GUI出现,虽然按钮仍然可以按下,但它不会再次进入代码。我从互联网上研究得到了这些代码片段,所以也许有些我不熟悉的错误。谁能看出我的努力有什么问题?为什么调试在上面的行中消失了,C#gui出现了?

谢谢!

感谢您的回答。我做了以下但是连接调用失败了。这是因为港口#?在c#中它是7898.在c ++中它是htons(7898),结果证明是另一个数字。

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;
}

在c#

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

TcpListener serverSocket = new TcpListener(localAddr,7898);

我阅读了htons文档并认为端口号没问题,而不是问题。那么它不连接? 再次感谢!

3 个答案:

答案 0 :(得分:1)

在C ++客户端调用bind之后,它必须调用connect。在成功建立连接之前,调用发送将不起作用。

答案 1 :(得分:0)

TcpListener.AcceptTcpClient是一个阻塞操作,意味着在客户端连接之前不会执行任何其他代码。因此,您无法继续调试,因为该调用永远不会完成。

GUI是响应式的,因为您将所有工作委托给后台线程。

答案 2 :(得分:0)

首先,发生连接错误后,调用WSAGetLastError()来获取实际错误。这可能会给你一些见解。其次,我怀疑你因为指定了无效的大小而得到10014错误。如果你传递sizeof(sockaddr)而不是sizeof(服务器),你可能会有更多的运气。