Saturday, March 19, 2016

Linux C Tcp Server with Windows Python and C# client

telnet localhost 107  ^] =exit (as tcp client) 
pgrep -a my_tcp_sever  pgrep my_tcp_server | xargs kill
Tool Eclipse Mars C/C++ 
fork() allow concurrent processing of client socket.

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>

#define SERVER_PORT 1067
struct sockaddr_in create_server()
{
        struct sockaddr_in server;
        server.sin_family=AF_INET;
        server.sin_addr.s_addr=htonl(INADDR_ANY);
        server.sin_port=htons(SERVER_PORT);
        return server;
}

void pass_through(int in, int out)
{
        unsigned char buf[1024];
        int c;
        while( (c=read(in,buf,1024))>0)
        {
                write(out,buf,c);
        }
}

int main(void) {
        struct sockaddr_in svr=create_server();
        int sok=socket(AF_INET,SOCK_STREAM,0);

    bind(sok,(struct sockaddr *)&svr,sizeof(svr));
    listen(sok,5);  // Listener queue
        puts("Listening at 1067.45..\n");

        struct sockaddr_in clnt;
        int clnt_len;
        int fd;  //connection descriptor
        while(1)
        {
                clnt_len= sizeof(clnt);
                fd=accept(sok,(struct sockaddr *)&clnt,&clnt_len);
                puts("client connected\n");
                if(fork()==0){
                  close(sok); // inside child process.
                  pass_through(fd,fd);
                }
                else
                  close(fd);// limit # descriptor can run out, close it
        }

        return EXIT_SUCCESS;
}
 a simple python client

#!/usr/bin/python3

from socket import *

s=socket(family=AF_INET,type=SOCK_STREAM);
s.connect(("192.168.0.108",1067));
m="this is a test"
s.send(m.encode('ascii'));
resp=s.recv(len(m))
print(resp.decode())
s.close()

C# client
            TcpClient tcp_c = new TcpClient();
            tcp_c.Connect("192.168.0.108", 1067);
            string msg = "message from C#";
            tcp_c.Client.Send(Encoding.ASCII.GetBytes(msg));
            byte[] buf = new byte[msg.Length];
            tcp_c.Client.Receive(buf);
            Console.WriteLine(Encoding.ASCII.GetString(buf));

No comments:

Post a Comment