简体   繁体   中英

vs2012 c# and unix c server socket communication

i'm writing a client program in c# vs2012 and server on linux raspbian in c. They are in the same network and client connects to the serv alright. The issue is, when i send something from client to serv, the serv doesn't react. I don't know whether my problem lies in the client or in the server.

the server code:

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PORTNUM 4510
#define MAXRCVLEN 255

void set_fifo(int *fifo1, int *fifo2)
{
    mkfifo("/tmp/fifo1", 0600); // 1 - Reading from serial
    mkfifo("/tmp/fifo2", 0600); // 2 - Writing to serial

    if((*fifo1 = open("/tmp/fifo1", O_RDONLY) < 0) || (*fifo2 = open("/tmp/fifo2", O_WRONLY) < 0))
    {
        error("ERROR opening FIFO\n");
        exit(1);
    }
}

int main(int argc, char *argv[])
{
    char msg[] = "Hello World !\n";
    char buffer[MAXRCVLEN];

    int fifo1, fifo2;
    set_fifo(&fifo1, &fifo2);

    int len = 0;
    struct sockaddr_in dest; /* socket info about the machine connecting to us */
    struct sockaddr_in serv; /* socket info about our server */
    int mysocket;            /* socket used to listen for incoming connections */
    socklen_t socksize = sizeof(struct sockaddr_in);

    memset(&serv, 0, sizeof(serv));           /* zero the struct before filling the fields */
    serv.sin_family = AF_INET;                /* set the type of connection to TCP/IP */
    serv.sin_addr.s_addr = htonl(INADDR_ANY); /* set our address to any interface */
    serv.sin_port = htons(PORTNUM);           /* set the server port number */    

    mysocket = socket(AF_INET, SOCK_STREAM, 0);

    /* bind serv information to mysocket */
    bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));

    /* start listening, allowing a queue of up to 1 pending connection */
    listen(mysocket, 1);
    int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);


    while(consocket)
    {
        printf("Incoming connection from %s\n", inet_ntoa(dest.sin_addr));

        recv(mysocket, buffer, MAXRCVLEN, 0)
        buffer[MAXRCVLEN] = '\0';
        printf("Message: %s", buffer);

        //send(consocket, msg, strlen(msg), 0); 
        consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
    }

    close(consocket);
    close(mysocket);
    return EXIT_SUCCESS;
}

I'm properly getting the "Incoming connection from" message after client connects. Client send method:

private void sendButton_Click(object sender, EventArgs e)
{
    try
    {
        string theMessageToSend = "Hello!";
        byte[] msg = Encoding.ASCII.GetBytes(theMessageToSend);
        senderSock.Send(msg);
    }
    catch (Exception exc) { MessageBox.Show(exc.ToString()); }
}

The try-catch doesn't throw anything.

And the method i use in client to connect to serv:

private void button1_Click(object sender, EventArgs e)
{
    connectButton.Text = "Connecting...";
    try
    {
        SocketPermission permission = new SocketPermission(
            NetworkAccess.Connect,    // Connection permission 
            TransportType.Tcp,        // Defines transport types 
            "",                       // Gets the IP addresses 
            SocketPermission.AllPorts // All ports 
            );
        permission.Demand();

        IPAddress ipAddr = IPAddress.Parse(ipInput.Text);
        int portNr = Convert.ToInt32(portTextBox.Text);
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, portNr);

        // Create one Socket object to setup Tcp connection 
        senderSock = new Socket(
            ipAddr.AddressFamily,// Specifies the addressing scheme 
            SocketType.Stream,   // The type of socket  
            ProtocolType.Tcp     // Specifies the protocols  
            );

        senderSock.NoDelay = false;   // Using the Nagle algorithm 

        // Establishes a connection to a remote host 
        senderSock.Connect(ipEndPoint);
        tbStatus.Text = "Socket connected to " + senderSock.RemoteEndPoint.ToString();

        connectButton.Enabled = false;
        connectButton.Text = "Connected";
        mainStart.Enabled = true;
    }
    catch (Exception exc) 
    { 
        MessageBox.Show(exc.ToString());
        connectButton.Text = "Connect";
    }
}

You are calling recv() on the wrong socket. Call it on consocket.

Also, I'm not sure that you're sending a C-style string with a terminating null? I know you've put a null at the end of the buffer, but still..

Also, recv() returns something that you need to take into account.

Also, if you want your server to correctly handle multiple clients, you will need to thread off the recv() loop and get rid of the accept() in it.

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