Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
The Java APIs for socket programming are part of the Java SE (Standard Edition). See java.io and
java.net.
Related Posts
Export a Java Project in Eclipse Neon to Executable JAR File with Manifest
Summary
Below is the Java source code for the server socket implementation.
The server socket is created in line 15 or line 17. See java.net.ServerSocket for more information.
package com.pgx.java.socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
else
new InputStreamReader(client.getInputStream()));
return this.server.getInetAddress();
return this.server.getLocalPort();
"Host=" + app.getSocketAddress().getHostAddress() +
app.listen();
new TCP/IP server socket using the provided ipAddress argument. If that argument is null or empty, it
will
try to resolve the local hosts’s IP address automatically. You may want to specify the server’s IP address
if you have multiple network
is used to set the IP address of the server socket. The local host address is used as an input parameter
for the ServerSocket constructor.
Below is the Java source code for the client socket implementation.
The client socket is created in line 15. See java.net.Socket for more information.
package com.pgx.java.socket;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
}
private void start() throws IOException {
String input;
while (true) {
input = scanner.nextLine();
out.println(input);
out.flush();
InetAddress.getByName(args[0]),
Integer.parseInt(args[1]));
client.start();
Requires the socket server’s IP address and the port number as arguments for opening a new socket
connection to the server using the java.net.Socket class.
It then uses the java.util.Scanner class to read keyboard input and to send the input as character data
over the
Here, the Java TCP/IP server and client socket application is exported to an executable JAR file named
TCPSocketTest.jar. For a quick description on how to create a JAR file in Eclipse, see:
Export a Java Project in Eclipse Neon to Executable JAR File with Manifest
Here, the server socket application will run on a machine with IP address 192.168.0.15.
Here, the client socket application will run on a machine with IP address 192.168.0.14.
To run the server socket from a terminal or Windows command prompt, use the java command:
When the server socket is running, it will print the host name (IP Address) and the socket port number.
MyMac:Java root$ ls
TCPSocketTest.jar
The socket port, here 53257, is given by the operating system and set automatically.
See line 17 in the MyServerSocket code and java.net.ServerSocket for more information.
Where the first input argument is the server’s IP address and the second one is the port number.
MyMac2:Java root$ ls
TCPSocketTest.jar
The server socket application will print a message when a new client connection is opened:
MyMac:Java root$ ls
TCPSocketTest.jar
MyMac2:Java root$ ls
TCPSocketTest.jar
MyMac2:Java root$ java -cp TCPSocketTest.jar com.pgx.java.socket.MyClientSocket 192.168.0.15 53257
The server socket application, will print the message that was received from the client.
MyMac:Java root$ ls
TCPSocketTest.jar
The Java server and client applications can be stopped by pressing CTRL + C.
Wireshark Download Page - Download Stable Release for Mac OS 10.6 and Later
After installation, run Wireshark and select a network interface to capture traffic on.
Here, the localhost’s Loopback interface lo0 is selected to monitor local traffic.
Wireshark - Select Network Interface for Traffic TCP/IP Capture
In the green filter field, enter the below pattern to filter the traffic by the server socket TCP port:
tcp.port == 53257
Send messages from the client- to the server socket to capture traffic.
To view the payload of a TCP packet, expand the Data node and click on the [Length: ..] item.
Wireshark - Capturing Java TCP/IP Server and Client Socket Traffic on Loopback Interface
In the previous example, text data messages are sent through the TCP/IP socket connection. In this
section, it is shown how to send binary data
such as an image with a Java TCP/IP server and client socket application. The below image from the
Porsche Media Gallery is used here:
Source: press.porsche.com/media/…/saphire_blue_carrera_cabriolet_gts_017.jpg
The client will read the image file from its file system and then send the binary data through the socket.
The below code shows a new socket program, called MyClientSocketBinary which uses a class named
MyFileReader to read an image file and then send its binary data over a socket connection.
package com.pgx.java.socket;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
//
//
//
//
for (byte i : data) {
this.socket.getOutputStream().write(i);
/**
* Requires 3 arguments:
* @param args
* @throws Exception
*/
InetAddress.getByName(args[0]),
Integer.parseInt(args[1]));
client.sendFile(args[2]);
}
The source code of the Java class MyFileReader is shown below.
Refer to the Java documentation for usage of: File, FileInputStream and BufferedInputStream.
package com.pgx.java.socket;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
int bytesRead = 0;
int b;
fileData[bytesRead++] = (byte)b;
br.close();
return fileData;
}
/**
* For testing:
*/
//
//
The main method is for testing here. It reads the contents of a file and prints the number of bytes read.
The modified version of the server, named MyServerSocketBinary reads the incoming binary data from
the socket connection and then writes it to a JPEG file on its file system disk using a class named
MyFileWriter.
package com.pgx.java.socket;
import java.io.BufferedInputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServerSocketBinary {
else
//
//
//
//
bis.close();
//
//
client.close();
return this.server.getInetAddress();
return this.server.getLocalPort();
"Host=" + app.getSocketAddress().getHostAddress() +
package com.pgx.java.socket;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
int bytesWritten = 0;
int b;
bos.write(b);
bytesWritten++;
}
bos.close();
return bytesWritten;
/**
* For testing:
*/
//
// Read file
//
//
//
The main method is for testing here. It reads the contents of a file and creates an identical copy of it.
The binary socket server program is started on a machine with IP address 192.168.56.1.
MyMac:Java root$ ls
TCPSocketTest.jar
The binary socket client program is started on a machine with IP address 192.168.56.2.
The image file to send is located in the same folder as the TCPSocketTest.jar file.
MyMac2:Java root$ ls
TCPSocketTest.jar SAPHIRE_BLUE_CARRERA_CABRIOLET_GTS_017.jpg
The above console shows the output when running the client. It will read the file, send its contents over
the socket connection, then close the socket and exit the program.
The server will read the incoming binary data, write it to a file named image-<TIMESTAMP>.jpg and then
exit.
MyMac:Java root$ ls
TCPSocketTest.jar
MyMac:Java root$
View the image on the server side machine to confirm it opens correctly. Or use Get Info in Finder on
Mac OS to view the meta data of the received JPG file (if it can’t be viewed / read, the JPG file is
corrupted).
View JPG Image Metadata and Preview using Mac OS Finder Get Info