# Best language for socket programming



## cryptid (Jul 20, 2008)

i need to learn socket programming to build simple client/server application for linux and windows platforms please suggest a language whose learning curve is easy... i check for tuts on C and C++ and i found it pretty hard to follow i guess i will need help was planning to take up some classes and i also herd about Ruby which is a cross platform interpreted language and i herd there are not much hasssels  when it comes down to socket programming...

i need to learn a language which will give me access to pretty low level stuff so that in futher i can develop more powerfull applications ..


----------



## QwertyManiac (Jul 21, 2008)

You can try out Ruby or Python (Or the likes - PERL/PHP)

But by the looks of your question, you are shying away from actually learning things before you attempt to implement, this will not get you anywhere if true.

I have little idea about network programming but I've written a basic application performing the client/server process in Python. You can read the below to valuate if the abstraction provided by Python is enough for your needs or not. (I'm using the default *socket module* provided by Python)

The server snippet:

```
import socket

address, buff = ("localhost", 21000), 2048

Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Sock.bind(address)

print "SERVER\n------\n"

while True:
    
    data, address = Sock.recvfrom(buff)
    if not data:
        print "Client stopped/exited."
        break
    else:
        print "Recieved the message:", data

Sock.close()
```
The Client snippet:

```
import socket

address = ("localhost", 21000)

Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print "CLIENT\n------\n"

while True:
    data = raw_input("Enter a message: ")
    if not data:
        Sock.sendto("", address)
        break
    else:
        if Sock.sendto(data, address):
            print "Sent message:", data, "to", address[0], "at port", address[1]
        else:
            print "Could not send the message. Retry."

Sock.close()
```
Input (Client side) [Example]:

```
CLIENT
------

Enter a message: hello
Sent message: hello to localhost at port 21000
Enter a message: world
Sent message: world to localhost at port 21000
```
Output (Server side) [Example]:

```
SERVER
------

Recieved the message: hello
Recieved the message: world
```
In Colleges they usually teach network programming in C/C++. You get more direct access to all the low-level stuff in those languages.


----------



## cryptid (Jul 21, 2008)

seems pretty nice.... the thing is that C/C++ network programming is not coverd in out engg syllabus anyways i've been reading up on a some ebooks i got my hands on so it make take me some more time to decide on which language i should be going with... mean while if u guys get anymore interesting finds let me know...


----------



## QwertyManiac (Jul 21, 2008)

What kind of interesting finds?


----------



## dheeraj_kumar (Jul 21, 2008)

I recommend WinSock for windows, and I'm not a penguin so dunno abt linux. WinSOck is not exactly easy to learn but its very flexible and powerful. You can go the WinAPI way or the highly abstracted .NET way.


----------



## Faun (Jul 21, 2008)

java is the way if u want to start with implementation without going beneath the abstraction.

I remember I wrote a threaded multi messenger on LAN using JAVA. It was fun, included some cool features too. but duh I always abandon my projects at 80%  dunno but thats me or i set high standards


----------



## ilugd (Jul 21, 2008)

t159. you remind me of the saying the last 20% of the project takes up 80% of hte time. you just didn't have the patience to stick to it for the 80%. . just a thought.
well c is good enough for network programming. but the thing is that if you want to learn network programming, you need to be comfortable in the language first, otherwise you will be verrrry confused. any language can be used imho.


----------



## Faun (Jul 21, 2008)

^^I meant that for extra features that I wished to add  But somehow never went back to add stars to complete that 20% . No one asked me to add those features and even the ones that i added. But it was me all the time working alone, though later on changed the stance to a lazy one.


----------



## ilugd (Jul 21, 2008)

^^ i have been there too. know what you are talking about.


----------



## chandru.in (Jul 22, 2008)

I'd go with T159's suggestion.  Java is very simple and yet pretty powerful in handling TCP/IP and UDP sockets.  No platform dependence (unlike Winsock or UNIX sockets) as it is pure TCP.  Also, most network programming will need multi-threading and Java's multi-threading capabilities are first-class.

I'm not very comfortable with Python.  But if I understand it right, a Java version of the server code given by QwertyManiac would be like this.

```
package demo;

import java.io.*;
import java.net.*;

public class SocketServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(21000);
            Socket connectedSocket = serverSocket.accept();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connectedSocket.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Received the message: " + line);
            }
            System.out.println("Client stopped/exited");
        } catch (Exception e) {
            System.out.println("Communication Error!");
        }
    }
}
```

The client code would look like this.


```
package demo;

import java.io.*;
import java.net.*;

public class SocketClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 21000);
            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    System.in));

            while (true) {
                System.out.print("Enter message: ");
                String message = reader.readLine();
                writer.println(message);
                System.out.println("Sent message: " + message + " to "
                        + socket.getRemoteSocketAddress() + " at port "
                        + socket.getPort());
            }
        } catch (Exception e) {
            System.out.println("Communication Error!");
        }
    }
}
```


----------



## quad_master (Jul 22, 2008)

+1 for java also its a goooooood platform independent lang


----------



## ray|raven (Jul 22, 2008)

^Yea , Use SWT for the GUI and you have urself native looking apps.


----------



## Sykora (Jul 22, 2008)

/me hates java on principle.

Learn the details in C/C++, then actually use it in python.


----------



## Garbage (Jul 22, 2008)

+1 more for Java... 

BTW, whats SWT ray|raven ?? Do u mean AWT ?? And if it is AWT, then instead of that, use Swing which is more advanced !


----------



## chandru.in (Jul 22, 2008)

Garbage said:


> +1 more for Java...
> 
> BTW, whats SWT ray|raven ?? Do u mean AWT ?? And if it is AWT, then instead of that, use Swing which is more advanced !


 
SWT stands for Standard Widget Toolkit.  It is more like a balance between AWT and Swing.

AWT - Fully peer based rendering.
Swing - Fully Java based rendering.
SWT - Peer based rendering when possible, if not uses Java based rendering.

It is a separate library and does not form part of the standard Java runtime.  Eclipse is developed using SWT.  There is one catch in using SWT.  You need to create separate packages of your application for each platform with the corresponding platform's SWT implementation.

Swing's native look and feel is improving (not as perfect as SWT).  It is also a Java spec standard and fully cross-platform. So unless perfect native look is of very high importance for the application, I'd recommend using Swing with the platform's native look and feel at runtime.

Anyway since the topic is about socket programming only, I dunno the exact GUI requirements of the OP.



Sykora said:


> /me hates java on principle.
> 
> Learn the details in C/C++, then actually use it in python.


 
For TCP/IP and UDP, i don't see Java hiding any important detail.  But if you want to use UNIX sockets or Winsock C/C++ is the way to go.  But then TCP/IP is pretty much standardised for modern network programming.

That said Qt (QSocket) does a good job at abstracting TCP/IP stack for C++.  I dunno about GTK so can't comment on that.


----------



## QwertyManiac (Jul 22, 2008)

Oh noes, its turning into a language war!

Best way: Learn everything, program in anything.


----------



## chandru.in (Jul 22, 2008)

QwertyManiac said:


> Oh noes, its turning into a language war!
> 
> Best way: Learn everything, program in anything.


Ooops!!  No never meant to turn it into one.  I still feel it is just a healthy debate of pros and cons.  I love all languages discussed here so far (though I'm not very comfortable with Python).

If I'm a reason for this to turn into a useless war, I'm sorry.


----------



## Garbage (Jul 22, 2008)

Thanks Chandru.in for clearing...


----------



## mehulved (Jul 22, 2008)

QwertyManiac said:


> Best way: Learn everything, program in anything.


----------



## Faun (Jul 22, 2008)

^^
may be you need comments and documentation too, so the other developer know the sh!t you meant and wrote


----------



## cryptid (Jul 22, 2008)

alright i think i will go the c/C++ way so please suggest some good books winsock programming.... i am currently reading Linux socket programming by example looks pretty decent so far i am able to understand the programs but was unable to compile it under my Ubuntu 8.04 with gcc 4 

please take a looks at it

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
int
main(int argc,char **argv) {
    int z;                   /* Status return code */
    int s[2];                /* Pair of sockets */
    /*
      * Create a pair of local sockets:
      */
    z = socketpair(AF_LOCAL,SOCK_STREAM,0,s);
    if ( z == -1 ) {
         fprintf(stderr,
             “%s: socketpair(AF_LOCAL,SOCK_STREAM,0)\n”,
             strerror(errno));
         return 1;           /* Failed */
    }
    /*
      * Report the socket file descriptors returned:
      */
    printf(“s[0] = %d;\n”,s[0]);
    printf(“s[1] = %d;\n”,s[1]);
    system(“netstat --unix -p”);
    return 0;
}



the error returned is ...


cryptid@black-box:~/Socket_sandbox$ gcc -o pro 01LST01.c
01LST01.c: In function ‘main’:
01LST01.c:13: error: stray ‘\342’ in program
01LST01.c:13: error: stray ‘\200’ in program
01LST01.c:13: error: stray ‘\234’ in program
01LST01.c:13: error: expected expression before ‘%’ token
01LST01.c:13: error: stray ‘\’ in program
01LST01.c:13: error: stray ‘\342’ in program
01LST01.c:13: error: stray ‘\200’ in program
01LST01.c:13: error: stray ‘\235’ in program
01LST01.c:16: error: stray ‘\342’ in program
01LST01.c:16: error: stray ‘\200’ in program
01LST01.c:16: error: stray ‘\234’ in program
01LST01.c:16: error: expected expression before ‘%’ token
01LST01.c:16: error: stray ‘\’ in program
01LST01.c:16: error: stray ‘\342’ in program
01LST01.c:16: error: stray ‘\200’ in program
01LST01.c:16: error: stray ‘\235’ in program
01LST01.c:17: error: stray ‘\342’ in program
01LST01.c:17: error: stray ‘\200’ in program
01LST01.c:17: error: stray ‘\234’ in program
01LST01.c:17: error: expected expression before ‘%’ token
01LST01.c:17: error: stray ‘\’ in program
01LST01.c:17: error: stray ‘\342’ in program
01LST01.c:17: error: stray ‘\200’ in program
01LST01.c:17: error: stray ‘\235’ in program


----------



## mehulved (Jul 22, 2008)

Well it's happening cos you did C-c C-v. Look at the ""


----------



## Faun (Jul 22, 2008)

its the "quotes and ticks" problem which happens while copying from ebooks
lolz...noob


----------



## mehulved (Jul 22, 2008)

No, it isn't ticks.


----------



## Faun (Jul 22, 2008)

^^you sure its not double quotes ?

"quotes and ticks is a general name to this problem coined by neo darwin"
lolz


----------



## ray|raven (Jul 23, 2008)

QwertyManiac said:


> Oh noes, its turning into a language war!



Die QwertyM for starting a language war 



Garbage said:


> +1 more for Java...
> 
> BTW, whats SWT ray|raven ?? Do u mean AWT ?? And if it is AWT, then instead of that, use Swing which is more advanced !



Like Chandru.in said , its another gui toolkit for Java.
The advantage over Swing is that , SWT lets the native system draw the widgets , so they're faster than swing widgets , and the look-n-feel is consistent. It also takes away some load from the JVM i guess.

The disadvantage is that , you gotta compile each platform's version with a compatible version of SWT.


----------



## QwertyManiac (Jul 23, 2008)

I never said a word against any language, and I gave an example in the one I could


----------

