Friday, October 22, 2010

A server client socket example in java

Well I wrote this in eclipse in preparation for a school project, the idea was to write a server that can take and talk to multiple connections at the same time, or send data to a specific client. You must import the package in eclipse to run unless you want to compile from command line.

Download It Here:
http://gitorious.org/simple-server-client-messaging-experiment/simple-server-client-messaging-experiment/trees/master

To start the server: navigate in the package explorer to src> MultiConnectionTests> MultiConnectionServer.java and  right click, run as "Java Application" you may get a firewall warning, just allow it. The server uses the console for its io.

To start a client: navigate in the package explorer to src>Tests>hostageclient.java and right click run as "Java Application". This uses a swing interface for its i/o. It take the ip of the server as a cmdline instruction and assumes localhost if none is given.

Once you have a server and one or many clients open you can start communicating. The client must talk to the server so all you have to do is type into the text box at the bottom of the applet window to send a message to the server. The server however can talk to all clients at once, or one at a time. Each client is given a number when he connects to the server, if you want to talk to a single client, then prefix your message with the space separated client number. EX:

server~$ 1 hi there client one

sends the message "hi there client one" to client 1. If you want to send a message to all clients, you simply dont put a number there.


server~$ hi there all

sends the message "hi there all" to all the clients.

Balling Eh?

No comments: