Methods to implement Java Socket Programming

To learn meaning of Java Sockets and Socket Programming check.
Java Sockets
//single one to one client

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

/*
Simple client using Java Sockets.

*/
public class SimpleClient {

/*
@param args
*/
public static void main(String[] args) {

// create a socket and find it to the host/port server is listening on.
String host;
int port;

if(args.length==0) {
host = “localhost”;
port = 9999;
} else {
host = args[0];
String portStr = args[1];
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
System.out.println(“Whoops, invalid port number. Will default to 9999”);
port = 9999;
}
}

try {
System.out.println(“Client will attempt connecting to server at host=”+ host +” port=”+ port +”.”);
Socket skt = new Socket(host,port);

// ok, got a connection. Let’s use java.io.* niceties to read and write from the connection.
BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));

PrintStream myOutput = new PrintStream(skt.getOutputStream());

boolean done = false;

while (!done) {

// prompt and read from console
System.out.print(“Enter a message, or enter “done” to quit: “);
String buf = consoleInput.readLine();

if(buf != null) {
if(buf.equalsIgnoreCase(“done”)) {
done = true;
} else {

// write something to the server.
myOutput.println(buf);

// see if the server echoes it back.
buf = myInput.readLine();
if(buf != null) {
System.out.println(“Client received [“+ buf + “] from the server!”);
}

}
} else {
done = true;
}
}

// we’re done, let’s get out of dodge!
skt.close();
System.out.println(“Client is exiting.”);

} catch (IOException ex) {
ex.printStackTrace();
System.out.println(“Whoops, something bad happened! I’m outta here.”);
}

}}

//single one to one server

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

/*
Simple server using Java Sockets.

*/
public class SimpleServer implements Runnable{

Socket csocket;

SimpleServer(Socket csocket){
this.csocket = csocket;
}

public static void main(String[] args) {

try {
// First we create a server socket and bind it to port 9999.
ServerSocket myServerSocket = new ServerSocket(9999);
// server processes incoming client connections forever…
while (true) {

// wait for an incoming connection…
System.out.println(“Server is waiting for an incoming connection on host=”);
System.out.print(InetAddress.getLocalHost().getCanonicalHostName()+” port=”+ myServerSocket.getLocalPort());

Socket skt = myServerSocket.accept();
new Thread(new SimpleServer(skt)).start();
}
} catch (IOException ex) {
ex.printStackTrace();
System.out.println(“Whoops, something bad happened! I’m outta here.”);
}
}

public void run(){

try{

// ok, got a connection. Let’s use java.io. niceties to read and write from the connection.
BufferedReader inputFromClient = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
PrintStream outputToClient = new PrintStream(csocket.getOutputStream());

boolean connectionClosed = false;
while(!connectionClosed) {
// attempt to read input from the stream.
String buf = inputFromClient.readLine();

// if we got input, print it out and write a message back to the remote client..
if (buf != null) {
System.out.println(“Server read: [“+ buf + “]”);
outputToClient.println(buf);
} else {
connectionClosed = true;
}
}

// close the connection.
csocket.close();
System.out.println(“Connection to client closed. Server is now going to wait for another connection.”);

} catch (IOException ex) {
ex.printStackTrace();
System.out.println(“Whoops, something bad happened! I’m outta here.”);
}

}

}

Author: Arun Singh

Learning is an Habit.