Socket Programming in Java
Socket Programming in Java
This article describes a very basic one-way Client and Server setup where a Client connects, sends messages to server and the
server shows them using socket connection. There’s a lot of low-level stuff that needs to happen for these things to work but the
Java API networking package (java.net) takes care of all of that, making network programming very easy for programmers.
Client Side Programming
Establish a Socket Connection
To connect to other machine we need a socket connection. A socket connection means the two machines have information about
each other’s network location (IP Address) and TCP port.The java.net.Socket class represents a Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
First argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code will run on single stand-alone
machine).
Second argument – TCP Port. (Just a number representing which application to run on a server. For example, HTTP runs on
port 80. Port number can be from 0 to 65535)
Communication
To communicate over a socket connection, streams are used to both input and output the data.
Closing the connection
The socket connection is closed explicitly once the message to server is sent.
In the program, Client keeps reading input from user and sends to the server until “Over” is typed.
import java.net.*;
import java.io.*;
Server Programming
Establish a Socket Connection
To write a server application two sockets are needed.
A ServerSocket which waits for the client requests (when a client makes a new Socket())
A plain old Socket socket to use for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Close the Connection
After finishing, it is important to close the connection by closing the socket as well as input/output streams.
import java.net.*;
import java.io.*;
socket = server.accept();
System.out.println("Client accepted");
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
The accept() method blocks(just sits there) until a client connects to the server.
Then we take input from the socket using getInputStream() method. Our Server keeps receiving messages until the Client
sends “Over”.
After we’re done we close the connection by closing the socket and the input stream.
To run the Client and Server application on your machine, compile both of them. Then first run the server application and then
run the Client application.