简体   繁体   中英

Sending message from C# client to C server

I'm fairly new to socket programming, but, using an online tutorial, I've successfully sent a short string from one machine to another using C.

The problem I'm having is with trying to send a string from a client written in C#. The server (written in C) prints out a blank/empty string.

Here is the C code that runs on the "server" machine (in this case a router running OpenWRT):

int main(int argc, char *argv[])
{
    int listenfd = 0, connfd = 0;
    struct sockaddr_in serv_addr;

    char recvBuff[1025];

    int bytesRead;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, '0', sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(1234);

    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    printf("Listening for string on port 1234...\n");

    listen(listenfd, 10);

    while(1)
    {
        connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);

        bytesRead = recv(connfd, recvBuff, 1024, 0);    // Receive string

        if (bytesRead < 0)
        {
            printf("Error reading from stream\n");
        }

        recvBuff[bytesRead] = 0;    // null-terminate the string

        printf("%d:%s\n", bytesRead, recvBuff);

        close(connfd);
        sleep(1);
     }
}

When sending this little server a string from another C program it works exactly as expected (prints the string out then waits for another one). [ Note: I don't think the C client's code is relevant, but I can post it if need be ]

However, when trying to send it a string from a C# program (copied below), the server prints out 0: (ie 0 bytes read, followed by an empty string) and I can't for the life of me figure out what the issue is. Both apps are pretty straightforward, so I'm assuming I should be using something other than WriteLine (I've also tried Write but to no avail).

C# Client:

namespace SocketTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("10.45.13.220", 1234);

            Stream stream = client.GetStream();

            StreamWriter writer = new StreamWriter(stream);

            writer.WriteLine("Testing...");

            client.Close();
        }
    }
}

To null terminate a string use

recvBuff[bytesRead] = '\0'; 

And call close on writer (which causes the writer to flush any pending bytes)

writer.WriteLine("Testing...");
writer.Close();
client.Close();

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