- Java Networking: Socket
- Creating a Socket
- Writing to a Socket
- Reading from a Socket
- Closing a Socket
- Reading from and Writing to a Socket
- Socket read
- Socket input and out stream
- Wrap DataOutputStream and DataInputStream for Socket
- Read Object from Socket
- Read float number from a Socket
- Next chapter.
- How to Read Data from a Socket Using Java
Java Networking: Socket
In order to connect to a server over the internet (via TCP/IP) in Java, you need to create a java.net.Socket and connect it to the server. Alternatively you can use a Java NIO SocketChannel, in case you prefer to use Java NIO.
Creating a Socket
This code example connects to the server with IP address 78.46.84.171 on port 80. That server happens to be my web server (www.jenkov.com), and port 80 is the web servers port.
Socket socket = new Socket("78.46.84.171", 80);
You can also use a domain name instead of an IP address, like this:
Socket socket = new Socket("jenkov.com", 80);
Writing to a Socket
To write to a Java Socket you must obtain its OutputStream . Here is how that is done:
Socket socket = new Socket("jenkov.com", 80); OutputStream out = socket.getOutputStream(); out.write("some data".getBytes()); out.flush(); out.close(); socket.close();
Don’t forget to call flush() when you really, really want the data sent across the internet to the server. The underlying TCP/IP implementation in your OS may buffer the data and send it in larger chunks to fit with with the size of TCP/IP packets.
Reading from a Socket
To read from a Java Socket you will need to obtains its InputStream . Here is how that is done:
Socket socket = new Socket("jenkov.com", 80); InputStream in = socket.getInputStream(); int data = in.read(); //. read more data. in.close(); socket.close();
Keep in mind that you cannot always just read from the Socket’s InputStream until it returns -1, as you can when reading a file. The reason is that -1 is only returned when the server closes the connection. But a server may not always close the connection. Perhaps you want to send multiple requests over the same connection. In that case it would be pretty stupid to close the connection.
Instead you must know how many bytes to read from the Socket’s InputStream . This can be done by either the server telling how many bytes it is sending, or by looking for a special end-of-data character.
Closing a Socket
When you are done using a Java Socket you must close it to close the connection to the server. This is done by calling the Socket.close() method, like this:
Socket socket = new Socket("jenkov.com", 80); socket.close();
Reading from and Writing to a Socket
Let’s look at a simple example that illustrates how a program can establish a connection to a server program using the Socket class and then, how the client can send data to and receive data from the server through the socket.
The example program implements a client, EchoClient , that connects to an echo server. The echo server receives data from its client and echoes it back. The example EchoServer implements an echo server. (Alternatively, the client can connect to any host that supports the Echo Protocol.)
The EchoClient example creates a socket, thereby getting a connection to the echo server. It reads input from the user on the standard input stream, and then forwards that text to the echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server.
Note that the EchoClient example both writes to and reads from its socket, thereby sending data to and receiving data from the echo server.
Let’s walk through the program and investigate the interesting parts. The following statements in the try -with-resources statement in the EchoClient example are critical. These lines establish the socket connection between the client and the server and open a PrintWriter and a BufferedReader on the socket:
String hostName = args[0]; int portNumber = Integer.parseInt(args[1]); try ( Socket echoSocket = new Socket(hostName, portNumber); // 1st statement PrintWriter out = // 2nd statement new PrintWriter(echoSocket.getOutputStream(), true); BufferedReader in = // 3rd statement new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); BufferedReader stdIn = // 4th statement new BufferedReader( new InputStreamReader(System.in)) )
The first statement in the try -with resources statement creates a new Socket object and names it echoSocket . The Socket constructor used here requires the name of the computer and the port number to which you want to connect. The example program uses the first command-line argument as the name of the computer (the host name) and the second command line argument as the port number. When you run this program on your computer, make sure that the host name you use is the fully qualified IP name of the computer to which you want to connect. For example, if your echo server is running on the computer echoserver.example.com and it is listening on port number 7, first run the following command from the computer echoserver.example.com if you want to use the EchoServer example as your echo server:
Afterward, run the EchoClient example with the following command:
java EchoClient echoserver.example.com 7
The second statement in the try -with resources statement gets the socket’s output stream and opens a PrintWriter on it named out . Similarly, the third statement gets the socket’s input stream and opens a BufferedReader on it named in . The example uses readers and writers so that it can write Unicode characters over the socket. If you are not yet familiar with the Java platform’s I/O classes, you may wish to read Basic I/O.
The next interesting part of the program is the while loop. The loop reads a line at a time from the standard input stream with the BufferedReader object stdIn , which is created in the fourth statement in the try -with resources statement. The loop then immediately sends the line to the server by writing it to the PrintWriter connected to the socket:
String userInput; while ((userInput = stdIn.readLine()) != null)
The last statement in the while loop reads a line of information from the BufferedReader connected to the socket. The readLine method waits until the server echoes the information back to EchoClient . When readline returns, EchoClient prints the information to the standard output.
The while loop continues until the user types an end-of-input character. That is, the EchoClient example reads input from the user, sends it to the Echo server, gets a response from the server, and displays it, until it reaches the end-of-input. (You can type an end-of-input character by pressing Ctrl-C.) The while loop then terminates, and the Java runtime automatically closes the readers and writers connected to the socket and to the standard input stream, and it closes the socket connection to the server. The Java runtime closes these resources automatically because they were created in the try -with-resources statement. The Java runtime closes these resources in reverse order that they were created. (This is good because streams connected to a socket should be closed before the socket itself is closed.)
This client program is straightforward and simple because the echo server implements a simple protocol. The client sends text to the server, and the server echoes it back. When your client programs are talking to a more complicated server such as an HTTP server, your client program will also be more complicated. However, the basics are much the same as they are in this program:
- Open a socket.
- Open an input stream and output stream to the socket.
- Read from and write to the stream according to the server’s protocol.
- Close the streams.
- Close the socket.
Only step 3 differs from client to client, depending on the server. The other steps remain largely the same.
Socket read
The following code uses a Socket to connect to a domain.
import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; /* j av a 2s . c o m*/ public class Main < public static void main(String[] argv) throws Exception < InetAddress addr = InetAddress.getByName("java2s.com"); int port = 80; SocketAddress sockaddr = new InetSocketAddress(addr, port); Socket sock = new Socket(); int timeoutMs = 2000; // 2 seconds sock.connect(sockaddr, timeoutMs); > >
Socket input and out stream
import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; // j a va2s.com class Whois < public static void main(String args[]) throws Exception < int c; Socket s = new Socket("internic.net", 43); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); String str = "java2s.com\n"; byte buf[] = str.getBytes(); out.write(buf); while ((c = in.read()) != -1) < System.out.print((char) c); > s.close(); > >
Wrap DataOutputStream and DataInputStream for Socket
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /* jav a 2s . c o m*/ public class Main < public static void main(String[] args) throws Exception < Socket client = new Socket("127.0.0.1", 80); System.out.println("Just connected to " + client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readUTF()); client.close(); > >
Read Object from Socket
import java.io.ObjectInputStream; import java.net.Socket; import java.util.Hashtable; /*from j a v a2 s . c o m*/ public class Main< public static void main(String[] args) throws Exception < Socket sock = new Socket(args[0], 1234); ObjectInputStream ois = new ObjectInputStream(sock.getInputStream()); Hashtable hash = (Hashtable) ois.readObject(); System.out.println(hash); ois.close(); sock.close(); > >
Read float number from a Socket
import java.io.DataInputStream; import java.net.Socket; /*from j a v a2s . co m*/ public class Main < public static void main(String[] args) throws Exception < Socket sock = new Socket(args[0], 1234); DataInputStream dis = new DataInputStream(sock.getInputStream()); float f = dis.readFloat(); System.out.println("PI \n"; zip.write(line.getBytes(), 0, line.length()); > zip.finish(); zip.close(); sock.close(); > >
Next chapter.
What you will learn in the next chapter:
How to Read Data from a Socket Using Java
In this article, we show how to read data from a socket using Java.
To connect to another machine, we need a Socket connection.
A Socket is an object that represents a network connection between 2 machines. So that the 2 pieces of software know about each other and are able to communicate with one another.
When referencing Socket connections, usually one machine is the server and the other machine is the client. The client is the machine connecting to and communicating with the server. In exchange, the server sends information back to the client.
To make a Socket connection, you need to know 2 things about the server, its network location (IP address) and what port it is running on.
So once the 2 machines know each other’s network location and port number, they can communicate with each other.
To communicate over a Socket connection, you use streams.
This is shown in the code below.
So in the above code, we import the java.io package because this has the InputStreamReader and BufferedReader definitions. We also must import the java.net package, which contains the Socket class.
We create a public class named ReadSocket.
In this class, we create our main method, which is where our program executes.
In this method, we use exception handling using try and catch statements.
We create a Socket object from the Socket class. Inside of this Socket object, we declare the IP address and the port number of the server we are referencing. In the code above, the IP address is 127.0.0.1 and the port number is 4242.
Next, we create an instance of the InputStreamReader class named streamReader. We pass in the parameter, sock.getInputStream(). This gets the input stream of the socket object that we’ve created.
We then create a BufferedReader object named reader and pass in the parameter, streamReader. This ties in the input stream from the socket object we’ve created to the BufferedReader class so that we can read the data from the socket.
We then create a variable named value and set it equal to reader.readLine(). This reads in the value from the BufferedReader object, reader.
We then output the value and close the BufferedReader object once done.
We have a catch statment for the reason of exception handling.
And this is all that is necessary to read a socket using Java.