View Feed
group-icon
Java Developers
Community of Java Developers: Get Java Programming Help from fellow Java Developers across the world.
560 Members
Join this group to post and comment.
shalini_goel14
shalini_goel14 • Mar 1, 2009

Basics of Socket Programming in Java

BASIC SOCKET PROGRAMMING IN JAVA

Client/Server
A server is anything that has some resources that can be shared.
A client is simply any other entity that wants to gain access to a particular server. The interaction between client and server is just like the interaction between a lamp and an electrical socket. The power grid of the house is the server and the lamp is a power client.
What exactly is a socket?
Can say, a network socket is lot like an electrical socket.
The notion of a socket only allows a single computer to serve many different clients at once, as well as serving many different types of information. This is managed by the introduction of a port which is a numbered socket on a particular machine. A server process is said to β€œlisten” to a port until a client connects to it. A server is allowed to accept multiple clients connected to the same port number, although each session is unique. To manage multiple client connections, a server process must be multithreaded or must have some other means of multiplexing simultaneous I/O.
For more information about it check the following link. It is very informative for those who are interested in this topic. πŸ˜€

Lesson: All About Sockets (The Javaβ„’ Tutorials > Custom Networking)

TCP/IP Client Sockets

These ae used to implement reliable,bidirectional, persistent, point-to-point stream based connections between hosts on the Internet. A Socket can be used to connect Java's I/O system to other programs that may reside either on the local or any other machine on the internet.

There are two kind of TCP/IP sockets in Java
1. For Servers- ServerSocket

ServerSocket class is designed to be a "listener" whcih wait for clients to connect before doing anything. This class is used to create servers that listen for either local or remote client programs to connect to them on published ports.

Constructors of this class:

a) ServerSocket( int port)
Creates server socket on the specified port with a queue length of 50.

b) ServerSocket(int port,int maxQueue)
Create a server socket on the specified port with a maximum queue length of maxQueue

c) ServerSocket(int port, int maxQueue, InetAddress localAddress)
Create a server socket on the specified port with a maximum queue length of maxQueue .On a multihomes host, localAddress specifies the IP address to which this socket binds.

All constructors above reflect the port number that we want to accept connections on and optionally how long we want the queue for said port to be.

ServerSocket has a method called as accept() which is a blocking call that will wait for a client to intiate communications and the return the normal Socket that is then used for communication with the client.

2. for Clients - Socket

The Socket class is designed to connect server sockets and initiate protocol exchanges.

The Socket object establishes a connection between the client and server. There are two constructors that can be used to create client sockets.

a) Socket(String hostName, int port)
Creates a socket connecting the local host to the named host and port

b) Socket(InetAddress ipAddress, int port)
Creates a port using a preexisting InetAddress object and a port

Few more things related to the Socket

a) InetAddress getInetAddress()->Returns the InetAddress associated with the Socket object .

b) int getPort()->Returns the remote port to which the invoking Socket object is connected.

c) int getLocalPort() -> Returns the local port to which the invoking Socket object is connected.

d) nputStream geInputStream() -> Returns the InputStream associated with the invoking socket.

e) OutputStream geOutputStream() -> Returns the OutputStream associated with the invoking socket.

Source: Complete Reference -by Herbert Schildt

Programming part is yet to come. Please wait. πŸ˜€

Hope the given link will clear all your doubts about this topic. If still any Please feel free to ask and add more information here if you have anything to share here.πŸ˜€
durga ch
durga ch • Mar 1, 2009
nice one Shalini.. πŸ˜€
ms_cs
ms_cs • Mar 2, 2009
Why dont you proceed further? In java number of features are available. SocketProgramming is one of the important one...
shalini_goel14
shalini_goel14 • Mar 2, 2009
ms_cs
Why dont you proceed further? In java number of features are available. SocketProgramming is one of the important one...
Please wait ms_cs, I will do so soon. Just the things are not working fine on my side. πŸ˜”
Yamini L
Yamini L • Mar 3, 2009
shalini_goel14
Programming part is yet to come. Please wait. πŸ˜€

Hope the given link will clear all your doubts about this topic. If still any Please feel free to ask and add more information here if you have anything to share here.πŸ˜€
Mam, i have also learned about Socket Programming in my last sem..I have a simple UDP chat program(Client and Server Communication)..I thought i can share it with you all..Here is my code..

CLIENT

[FONT=Sylfaen][FONT=Verdana]/*client.java*/[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]import java.io.*;[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]import java.net.*;[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]class client[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]{[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]public static void main(String args[])[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]{[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]String data;[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]try[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]{[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]DatagramSocket s=new DatagramSocket();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]do[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]{[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]System.out.println("Enter the data");[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]DataInputStream dis=new DataInputStream(System.in);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]InetAddress ip=InetAddress.getByName("");[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]byte[] senddata=new byte[1024];[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]byte[] receivedata=new byte[1024];[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]data=dis.readLine();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]senddata=data.getBytes();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]DatagramPacket sp=new DatagramPacket(senddata,senddata.length,ip,8050);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]s.send(sp);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]DatagramPacket rp=new DatagramPacket(receivedata,receivedata.length);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]s.receive(rp);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]String msg=new String(rp.getData());[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]System.out.println("From Server:"+msg);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]}[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]while(!data.equalsIgnoreCase("end"));[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]s.close();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]}[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]catch(Exception e){}[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]}}[/FONT][/FONT]
 
SERVER
[B][FONT=Sylfaen][FONT=Verdana]/*server.java*/[/FONT][/FONT][/B]
[FONT=Sylfaen][FONT=Verdana]import java.io.*;[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]import java.net.*;[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]class  server[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]{[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]public static void main(String args[])[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]{[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]try[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]{[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]DatagramSocket s=new DatagramSocket(8050);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]byte[] rd=new byte[1024];[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]byte[] sd=new byte[1024];[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]String sent;[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]do[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]{[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]DatagramPacket rp=new DatagramPacket(rd,rd.length);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]s.receive(rp);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]String data=new String(rp.getData());[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]System.out.println("Received from client:"+data);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]InetAddress ip=rp.getAddress();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]System.out.println("Address:"+ip);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]int port=rp.getPort();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]System.out.println("Port:"+port);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]System.out.println("Enter the data to send");[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]DataInputStream dis=new DataInputStream(System.in);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]sent=dis.readLine();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]sd=sent.getBytes();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,port);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]s.send(sp);[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]}[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]while(!sent.equalsIgnoreCase("end"));[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]s.close();[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]}catch(IOException e){}[/FONT][/FONT]
[FONT=Sylfaen][FONT=Verdana]}}[/FONT][/FONT]
 
OUTPUT

C:\jdk1.6.0_06\bin>javac server.java
C:\jdk1.6.0_06\bin>java server
Received from client: hi

Address:/127.0.0.1
Port: 1541
Enter the data to send
hello
Received from client: How are you?

Address:/127.0.0.1
Port: 1541
Enter the data to send
Fine


C:\jdk1.6.0_06\bin>javac client.java
C:\jdk1.6.0_06\bin>java client
Enter the data
hi
From Server: hello

Enter the data
How are you?
From Server: Fine

Enter the data
end
shalini_goel14
shalini_goel14 • Mar 3, 2009
Hey Well done miniy! I am becoming your fan man. 😁 😁

ok so you have given UDP sockets program, just wait for my TCP Sockets program.

PS: Just now I repaired few problems in my netbeans. I wish it will work within an hour. πŸ˜€
Yamini L
Yamini L • Mar 3, 2009
shalini_goel14
Hey Well done miniy! I am becoming your fan man. 😁 😁
Mam,just wanted to tell you that i am a girl..😁I wil aslo try to post my TCP Socket Program....
shalini_goel14
shalini_goel14 • Mar 3, 2009
miniy
Mam,just wanted to tell you that i am a girl..😁I wil aslo try to post my TCP Socket Program....
ok miniy, I am sorry for that "man" πŸ˜‰

Well I will wait for your TCP Socket Program. One more thing I would like to add, it would look better if you can show the output in command prompt and include them as images here. Good you have made my work easier. πŸ˜€
Yamini L
Yamini L • Mar 3, 2009
Yeah sure..I will do what you said mam..Thanks for the good words....:smile:
babloo0311
babloo0311 • Mar 3, 2009
Hello shalini, thanks you have done a good job
Yamini L
Yamini L • Mar 3, 2009
Well,here is a very small TCP socket program(Client Server Communication)..In this program,just a message is sent from client side to server and vice versa..Classes for creating sockets do vary with TCP and UDP(we use ServerSocket class and Socket class in TCP whereas in UDP we use DatagramSocket class)..



CLIENT

import java.io.*;
import java.net.*;
class clientt
{
public static void main(String args[]) throws SocketException,IOException
{
Socket s=new Socket("localhost",8080);
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println("Hello from client side");
DataInputStream dis=new DataInputStream(s.getInputStream());
System.out.println(dis.readLine());
ps.close();
}
}
 
SERVER

import java.io.*;
import java.net.*;
class servert
{
public static void main(String args[])throws SocketException,IOException
{
ServerSocket ss=new ServerSocket(8080);
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
System.out.println(dis.readLine());
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println("Hello from server side");
ps.close();
}
}

OUTPUT

SERVER

E:\yamini>javac servert.java
Note: servert.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
E:\yamini>java servert
Hello from client side
E:\yamini>

CLIENT

E:\yamini>javac clientt.java
Note: clientt.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
E:\yamini>java clientt
Hello from server side
E:\yamini>


@Shalini:Mam, I tried to give the output as command prompt images..But after inserting the image,i am unable to view it in the post😲..I will try to fix it soon and get it in the format u have mentioned:smile:..
shalini_goel14
shalini_goel14 • Mar 4, 2009
Good miniy 😁

What about s.close(); statement. I guess closing socket is also required in the code.

One more task for you-Can you find some time to explain your programs here so that rest of the CEans here can get benefitted. πŸ˜€

PS: @Yamini Would you like to work for any of CE projects ? πŸ˜€
Hey shalini and Miniy can you please tell me what are the pre- requisites to learn this socket programming?

Since i dont want to post silly questions , its better if we have some pre - requisites also included such that i can come back and then post my questions here.
πŸ˜•
Yamini L
Yamini L • Mar 4, 2009
shalini_goel14
One more task for you-Can you find some time to explain your programs here so that rest of the CEans here can get benefitted. πŸ˜€

PS: @Yamini Would you like to work for any of CE projects ? πŸ˜€
Yeah,I will try to find some time to explain those 2 programs:smile:..
Mam,I would like to work for CE projects(but i require guidance from you all)..As of now,I have my project reviews and university exams approaching(march and april)..Hence,I am not sure whether i will be able to spend more time on CE like now..πŸ˜•πŸ˜•(bit confused)..
shalini_goel14
shalini_goel14 • Mar 4, 2009
English-Scared
Since i dont want to post silly questions
According to me prerequisite to read what I typed is you know basic English and know how to search on google for terms that you don't understand and even then not satisfied ask here. For me no question is silly. You can ask any question. This will give us idea to tell you better whether you are interested in this topic in or just showing off. Your queries will be answered according to your knowledge level and interest in the topic. ok

miniy
Yeah,I will try to find some time to explain those 2 programs:smile:..
Mam,I would like to work for CE projects(but i require guidance from you all)..As of now,I have my project reviews and university exams approaching(march and april)..Hence,I am not sure whether i will be able to spend more time on CE like now..πŸ˜•πŸ˜•(bit confused)..
Sure miniy, no issues. First complete your final year. πŸ˜€
Yamini L
Yamini L • Mar 4, 2009
@Shalini: Mam, I have just tried to explain that UDP chat program..I have also mentioned here about the classes that are used for udp..:smile:Hope this would help others..

Socket Programming

Socket as you all know,is a connection between two hosts.A Socket can perform following operations

vConnect to a remote machine
vSend data
vReceive Data
vClose a machine
vBind to port
vListening for informing data
vAccept connections from remote machines on bound port

Life Cycle of a Socket

vA new Socket is created with help of Socket constructor
vA connection to remote host is tried by Socket
vAfter connection establishment both local and remote hosts can exchange information.
vWhen transmission is complete,one or both sides can close the connection.

The main difference between User Datagram Protocol(UDP) and Transmission Control Protocol(TCP) is that UDP provides a connectionless,unrealibe service(ensures quick delivery) whereas TCP provides a Connection Oriented,Reliable(flow control,error control)service..

JAVA’s implementation of UDP is split into 2 classes

vDatagramPacket – to stuff bytes of data into UDP packets called datagram and to unstuff received datagrams.

vDatagramSocket- to send as well as to receive UDP datagrams.


DatagramPacket class

Constructors for receiving Datagrams

vPublic DatagramPacket(byte[] buffer,int length)
vPublic DatagramPacket(byte[]buffer,int offset,int length)

Constructors for sending Datagrams

vPublic DatagramPacket(byte[]data,int length,InetAddress destination,int port)
vPublic DatagramPacket(byte[]data,int offset,InetAddress destination,int port)


Five methods are used to retrieve different parts of a Datagram namely.

ØgetAddress() {Returns InetAddress object or address of machine}
ØgePort() { returns an integer specifying port number}
ØgetData() {Returns a byte array containing data from datagream}
ØgetLength() {Returns number of bytes in datagram)
ØgetOffset() {Returns point in the array returned by getData() where the data from datagram begins}


We have also got following set methods such as setData(),setAddress(),setPort() and setLength() used for various purposes.

DatagramSocket class


All Datagram Sockets are bound to a local port on which they listen for incoming data ..

Constructors for DatagramSocket class

ØPublic DatagramSocket() throws SocketException
ØPublic DatagramSocket(int port)throws SocketException
ØPublic DatagramSocket(int port,InetAddress address)


We have 4 methods in this class..
Send()
Public void send(DatagramPacket dp)throws IOException
Used for sending datagrams

Receive()
Public void receive(DatagramPacket dp)throws IOException
Used for receiving Datagrams

Close()
Public void close()
Frees the port occupied by socket

getLocalPort()
public void getLocalPort()
returns the local port number on which the socket is listening

These are the 2 main classes(DatagramPacket and DatagramSocket) as far as UDP is concerned..



Explanation of UDP chat program

Client

vA DatagramSocket is first created.

vA DataInputStream object is created and using that data entered by the user is obtained

vInetAddress is obtained using getByName() method

vData obtained from InputStream need to be converted into bytes before transmission and this is made possible through getBytes() method.

vNow a new DatagramPacket is created is to stuff all the bytes into it and to send it to the server(done using send() function)

vOne more DatagramPacket is created just to receive the bytes of data from server (using receive() function)

vgetData() method gets the data from the bytes received and that is displayed on the console(converted to stream)..

vFinally socket is closed.(using close())

Server

vSame process occurs at server side(socket creation,DatagramPacket creation,receiving data from client side,sending data to client and so on)..Various get methods are used in the program (getPort(),getAddress(),getData())just to retrieve data sent by the client..

vThen DatagramPacket is created in server side and is sent to the client..(after stuffing bytes of data)

vFinally,Socket is closed..

vThis way Client and Server communication occurs using UDP..
shalini_goel14
According to me prerequisite to read what I typed is you know basic English and know how to search on google for terms that you don't understand and even then not satisfied ask here. For me no question is silly. You can ask any question. This will give us idea to tell you better whether you are interested in this topic in or just showing off. Your queries will be answered according to your knowledge level and interest in the topic. ok


Shalini : I asked the pre- requisites for every one of the forum interested in this one.
i can ask silly questions and you can answer them , but what if many people ask all minor questions which they can get through one single reading of a book or material or topic which you would suggest?

and me i will ask questions ..😎😎
shalini_goel14
shalini_goel14 • Mar 5, 2009
@Scared You need not to think of others. Others can ask questions here if have any. Well, I am waiting for your questions.

@Others You can ask any questions(Starting from S of Socket Programming πŸ˜‰ ). OK πŸ˜€
komputergeek
komputergeek • Mar 8, 2009
@shalini : I would like to know how to do audio streaming using socket programming.
shalini_goel14
shalini_goel14 • Mar 8, 2009
komputergeek
@shalini : I would like to know how to do audio streaming using socket programming.
Good question komputergeek, Please put some more light on what exactly is "audio streaming" πŸ˜€

Share this content on your social channels -