Transfer a file via Socket

A client module connects to a server then a file is sent to the client. This exemple is very simple with no authentication and hard-coded filename!

First a server module.


import java.net.*;
import java.io.*;

public class FileServer {
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");

Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);

// sendfile
File myFile = new File ("source.pdf");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}

The client module


import java.net.*;
import java.io.*;

public class FileClient{
public static void main (String [] args ) throws IOException {
int filesize=6022386; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");

// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("source-copy.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;

// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
}
}

How to validate IP address with regular expression

IP Address Regular Expression Pattern

^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.
([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$

Description:

^ #start of the line
( # start of group #1
[01]?\\d\\d? # Can be one or two digits. If three digits appear, it must start
either 0 or 1
# e.g ([0-9], [0-9][0-9],[0-1][0-9][0-9])
| # …or
2[0-4]\\d # start with 2, follow by 0-4 and end with any digit (2[0-4][0-9])
| # …or
25[0-5] # start with 2, follow by 5 and end with 0-5 (25[0-5])
) # end of group #2
\. # follow by a dot “.”

…. # repeat with 3 time (3x)
$ #end of the line

Whole combination means , digit from 0 to 255 and follow by a dot “.”, repeat 4 time and ending with no dot “.” Valid IP address format is “0-255.0-255.0-255.0-255″.
Java Regular Expression Example


package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPAddressValidator{

private Pattern pattern;
private Matcher matcher;

private static final String IPADDRESS_PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

public IPAddressValidator(){
pattern = Pattern.compile(IPADDRESS_PATTERN);
}

/**
* Validate ip address with regular expression
* @param ip ip address for validation
* @return true valid ip address, false invalid ip address
*/
public boolean validate(final String ip){
matcher = pattern.matcher(ip);
return matcher.matches();
}
}

IP address that match:

1. “1.1.1.1″, “255.255.255.255″,”192.168.1.1″ ,
2. “10.10.1.1″, “132.254.111.10″, “26.10.2.10″,
3. “127.0.0.1″

IP address that doesn’t match:

1. “10.10.10″ – must have 4 “.”
2. “10.10″ – must have 4 “.”
3. “10″ – must have 4 “.”
4. “a.a.a.a” – only digit is allow
5. “10.0.0.a” – only digit is allow
6. “10.10.10.256″ – digit must between [0-255]
7. “222.222.2.999″ – digit must between [0-255]
8. “999.10.10.20″ – digit must between [0-255]
9. “2222.22.22.22″ – digit must between [0-255]
10. “22.2222.22.2″ – digit must between [0-255]
Unit Test – IPAddressValidator


package com.mkyong.regex;

import org.testng.Assert;
import org.testng.annotations.*;

/**
* IPAddress validator Testing
* @author mkyong
*
*/
public class IPAddressValidatorTest {

private IPAddressValidator ipAddressValidator;

@BeforeClass
public void initData(){
ipAddressValidator = new IPAddressValidator();
}

@DataProvider
public Object[][] ValidIPAddressProvider() {
return new Object[][]{
new Object[] {"1.1.1.1"},new Object[] {"255.255.255.255"},
new Object[] {"192.168.1.1"},new Object[] {"10.10.1.1"},
new Object[] {"132.254.111.10"},new Object[] {"26.10.2.10"},
new Object[] {"127.0.0.1"}
};
}

@DataProvider
public Object[][] InvalidIPAddressProvider() {
return new Object[][]{
new Object[] {"10.10.10"},new Object[] {"10.10"},
new Object[] {"10"},new Object[] {"a.a.a.a"},
new Object[] {"10.0.0.a"},new Object[] {"10.10.10.256"},
new Object[] {"222.222.2.999"},new Object[] {"999.10.10.20"},
new Object[] {"2222.22.22.22"},new Object[] {"22.2222.22.2"},
new Object[] {"10.10.10"},new Object[] {"10.10.10"},
};
}

@Test(dataProvider = "ValidIPAddressProvider")
public void ValidIPAddressTest(String ip) {
boolean valid = ipAddressValidator.validate(ip);
System.out.println("IPAddress is valid : " + ip + " , " + valid);
Assert.assertEquals(true, valid);
}

@Test(dataProvider = "InvalidIPAddressProvider",
dependsOnMethods="ValidIPAddressTest")
public void InValidIPAddressTest(String ip) {
boolean valid = ipAddressValidator.validate(ip);
System.out.println("IPAddress is valid : " + ip + " , " + valid);
Assert.assertEquals(false, valid);
}
}

Unit Test – Result

IPAddress is valid : 1.1.1.1 , true
IPAddress is valid : 255.255.255.255 , true
IPAddress is valid : 192.168.1.1 , true
IPAddress is valid : 10.10.1.1 , true
IPAddress is valid : 132.254.111.10 , true
IPAddress is valid : 26.10.2.10 , true
IPAddress is valid : 127.0.0.1 , true
IPAddress is valid : 10.10.10 , false
IPAddress is valid : 10.10 , false
IPAddress is valid : 10 , false
IPAddress is valid : a.a.a.a , false
IPAddress is valid : 10.0.0.a , false
IPAddress is valid : 10.10.10.256 , false
IPAddress is valid : 222.222.2.999 , false
IPAddress is valid : 999.10.10.20 , false
IPAddress is valid : 2222.22.22.22 , false
IPAddress is valid : 22.2222.22.2 , false
PASSED: ValidIPAddressTest([Ljava.lang.String;@1d4c61c)
PASSED: InValidIPAddressTest([Ljava.lang.String;@116471f)

===============================================
com.mkyong.regex.IPAddressValidatorTest
Tests run: 2, Failures: 0, Skips: 0
===============================================

===============================================
mkyong
Total tests run: 2, Failures: 0, Skips: 0
===============================================

Reference

http://en.wikipedia.org/wiki/IP_address

Simple LAN Application

This example introduces you to Java socket programming. The server listens for a connection. When a connection is established by a client. The client can send data. In the current example the client sends the message “Hi my server”. To terminate the connection, the client sends the message “bye”. Then the server sends the message “bye” too. Finally the connection is ended and the server waits for an other connection. The two programs should be runned in the same machine. however if you want to run them in two different machines, you may simply change the adress “localhost” by the IP adress of the machine where you will run the server.

The server

import java.io.*;
import java.net.*;
public class Provider{
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider(){}
void run()
{
try{
//1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
//4. The two parts communicate via the input and output streams
do{
try{
message = (String)in.readObject();
System.out.println("client>" + message);
if (message.equals("bye"))
sendMessage("bye");
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
}while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Provider server = new Provider();
while(true){
server.run();
}
}
}

The client


import java.io.*;
import java.net.*;
public class Requester{
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Requester(){}
void run()
{
try{
//1. creating a socket to connect to the server
requestSocket = new Socket("localhost", 2004);
System.out.println("Connected to localhost in port 2004");
//2. get Input and Output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
//3: Communicating with the server
do{
try{
message = (String)in.readObject();
System.out.println("server>" + message);
sendMessage("Hi my server");
message = "bye";
sendMessage(message);
}
catch(ClassNotFoundException classNot){
System.err.println("data received in unknown format");
}
}while(!message.equals("bye"));
}
catch(UnknownHostException unknownHost){
System.err.println("You are trying to connect to an unknown host!");
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("client>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Requester client = new Requester();
client.run();
}
}