The client
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class HTCPCPClient {
public static void main(String[] args) throws IOException {
HTCPCPClient client = new HTCPCPClient();
System.out.println("WELCOME TO THE COFFEE POT APPLICATION!");
client.startClient();
}
private void startClient() throws IOException {
final String HOST = "localhost";
final int PORT_NUMBER = 4444;
Socket clientSocket = null;
PrintWriter outToServer = null;
BufferedReader in = null;
String serverSentence = null;
String clientSentence = null;
BufferedReader inFromServer = null;
// create new socket
clientSocket = new Socket(HOST, PORT_NUMBER);
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
do { // wait for 'QUIT'
// Create input stream
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
kbd = new Scanner(System.in);
clientSentence = null;
kbdInput = null;
System.out.println("Enter Method ( e.g. BREW )");
// next line of kbdInput from keybd.
kbdInput = kbd.nextLine().trim();
clientSentence = kbdInput + " coffee://127.0.0.1/pot-1 HTCPCP-new Accept-Additions: ";
clientSentence = clientSentence + "\nstart\n##";
// Send clientSentence to server
outToServer.println(clientSentence);
outToServer.flush();
System.out.println("\nMESSAGE FROM SERVER:");
do {
serverSentence = inFromServer.readLine();
System.out.println("\t" + serverSentence);
if (serverSentence.equals("##") == true) {
break;
}
} while (true);
// read and print message from server
} while (!clientSentence.contains("QUIT"));
// close connections
outToServer.close();
in.close();
inFromServer.close();
clientSocket.close();
}
}
Server Thread
import java.io.*;
import java.net.*;
public class HTCPCPClientWorker extends Thread {
Socket cwsocket = null;
public HTCPCPClientWorker(Socket cwsocket) {
super("ClientWorker");
this.cwsocket = cwsocket;
}
#Override
public void run() {
String clientSentence = null;
BufferedReader inFromClient = null;
PrintWriter outToClient = null;
try {
inFromClient = new BufferedReader(new InputStreamReader(cwsocket.getInputStream()));
outToClient = new PrintWriter(cwsocket.getOutputStream(), true);
} catch (IOException ex) {
System.err.println("Cannot create streams");
}
try {
do { // end when client says QUIT
StringBuffer clientInputLine[] = new StringBuffer[3];
clientInputLine[0] = new StringBuffer();
clientInputLine[1] = new StringBuffer();
// Get next message from client
for (int i = 0; i <= clientInputLine.length; i++) {
// read input line from BufferedReader
clientSentence = inFromClient.readLine();
// wait for EOF = ##
System.out.println("\tInput: " + clientSentence);
if (clientSentence.equals("##") == true) {
break;
}
clientInputLine[i].append(clientSentence);
if (clientSentence.contains("BREW")) {
outToClient.println("Message: " + clientSentence);
outToClient.println("HTCPCP-new 200 OK BREW START command completed.");
outToClient.println("Content-length: " + clientSentence.length());
outToClient.println("##");
outToClient.flush();
} else {
outToClient.println("Message: " + clientSentence);
outToClient.println("HTCPCP-new 400 Bad Request.");
outToClient.println("Content-length: " + clientSentence.length());
outToClient.println("##");
outToClient.flush();
}
} // end for loop
} while (!clientSentence.contains("QUIT"));
outToClient.println("GOODBYE!");
outToClient.flush();
System.out.println("\tClient has disconnected.");
cwsocket.close();
} catch (IOException e) {
e.printStackTrace();
}
} // end run
} end HTCPCPClientWorker.java
Client Console
WELCOME TO THE COFFEE POT APPLICATION!
Select an option:
1. Brew
2. Quit
1
Enter URL (e.g. BREW coffee://127.0.0.1/pot-1 HTCPCP-new )
BREW
MESSAGE FROM SERVER:
Message: BREW Accept-Additions:
HTCPCP-new 200 OK BREW START command completed.
Content-length: 23
##
Select an option:
1. Brew
2. Quit
1
Enter URL (e.g. BREW coffee://127.0.0.1/pot-1 HTCPCP-new )
BREW
MESSAGE FROM SERVER:
Message: start
HTCPCP-new 400 Bad Request.
Content-length: 5
##
Select an option:
1. Brew
2. Quit
Notice that the messages from the server are different despite the same URL being entered.
Any ideas where I'm going wrong?
In your server, you've got this on every iteration of your loop:
if (clientSentence.contains("BREW")) {
outToClient.println("Message: " + clientSentence);
outToClient.println("HTCPCP-new 200 OK BREW START command completed.");
outToClient.println("Content-length: " + clientSentence.length());
outToClient.println("##");
outToClient.flush();
} else {
outToClient.println("Message: " + clientSentence);
outToClient.println("HTCPCP-new 400 Bad Request.");
outToClient.println("Content-length: " + clientSentence.length());
outToClient.println("##");
outToClient.flush();
}
So the server will read "BREW" (etc), then spit out all that output, ending with ##. Your client displays all of that, and then asks for the next input... but the server won't have finished sending, because it will have read the next line of input, which is "start". It then prints out that second response, even though it's still reading the first request.
I suggest you finish reading the request then write out a response...
Note that your input loop should also have an exclusive upper bound, too:
for (int i = 0; i <= clientInputLine.length; i++) {
...
// This will blow up if i == clientInputLine.length
clientInputLine[i].append(clientSentence);
Related
There are two files (client file, server file) in this program that are supposed to be able to send and receive messages (utf-8 strings) to each other. Each file has a thread (one thread for client, one thread for server)
The client and the server connect on localhost with a port number (it should be the same port number when typing on the command prompt / mac terminal window)
However, the server is supposed to only send messages to all the other clients after receiving a message from a client. In other words, if a client sends a message to the server, the server cannot send that message back to the same client--it can only send messages to the different clients.
Another way to say it: Once a client is connected, it can send messages to the server. It will also receive from the server all messages sent from the other connected clients (not the messages sent from itself).
At runtime, there is supposed to be only one server (mac terminal / command prompt windows) but there can be multiple/infinite number of clients (mac terminal / command prompt windows)
Screenshot of error (server side):
Screenshot of error (client side):
Code of ChatServer.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
private static Socket socket;
public static void main(String args[])
{
Thread ChatServer1 = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
int port_number1 = 0;
int numberOfClients = 0;
boolean KeepRunning = true;
if(args.length>0)
{
port_number1 = Integer.valueOf(args[0]);
}
System.out.println("Waiting for connections on port " + port_number1);
try
{
ServerSocket serverSocket = new ServerSocket(port_number1);
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
ServerSocket serverSocket = new ServerSocket(port_number1);
//create a list of clients
ArrayList<String> ListOfClients = new ArrayList<String>();
//connect to client
socket = serverSocket.accept();
//add new client to the list, is this the right way to add a new client? or should it be in a for loop or something?
ListOfClients.add("new client");
numberOfClients += 1;
System.out.println("A client has connected. Waiting for message...");
ListOfClients.add("new client" + numberOfClients);
//reading encoded utf-8 message from client, decoding from utf-8 format
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
//relaying message to every other client besides the one it was from
for (int i = 0; i < ListOfClients.size(); i++)
{
if(ListOfClients.get(i)!="new client")
{
String newmessage = null;
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (socket != null)
{
socket.close ();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
ChatServer1.start();
}
}
Code of ChatClient.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
private static Socket Socket;
static int numberOfClients = 0;
public static void main(String args[])
{
//If I wanted to create multiple clients, would this code go here? OR should the new thread creation be outside the while(true) loop?
while (true)
{
String host = "localhost";
int numberOfClients = 0;
Thread ChatClient1 = new Thread ()
{
public void run()
{
try
{
//Client begins, gets port number, listens, connects, prints out messages from other clients
int port = 0;
int port_1number1 = 0;
int numberofmessages = 0;
String[] messagessentbyotherclients = null;
System.out.println("Try block begins..");
System.out.println("Chat client is running");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
if(args.length>0)
{
port = Integer.valueOf(port_number1);
}
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
Socket.connect(null);
System.out.println("Client has connected to the server");
for(int i = 0; i < numberOfClients; i++)
{
System.out.println(messagessentbyotherclients);
}
//client creates new message from standard input
OutputStream os = Socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input encoded in UTF-8 string format
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
input=null;
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//Sending the message to server
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
}
catch (IOException e)
{
e.printStackTrace();
}
}
};
ChatClient1.start();
}
}
}
These two errors have been covered many times and I've heard that the answer is to put the socket in a loop, which it already is in (while loop).
My question is: Is there a way to locate the errors before running it? Whenever I compile the program I don't get any errors in eclipse, but when I run it in the command prompt window / mac terminal, it does tell me that something is wrong. Or perhaps there's a line of code that I'm overlooking?
ServerSocket serverSocket = new ServerSocket(port_number1);
Place it once, before the while loop.
I'm trying to send a message to a particular client e.g. client 1 wants to send a message to client 2. Client 1 sends a message to the sever, the sever computes the answer and sends it to client 2 who displays it.
I'm using a HashMap to store each client. It compiles, but when I run it, it crashed when sending the message and displays
Problem with Communication Server
I believe the error is in the loop where I'm sending the message but I can't see what's wrong with it, do I need separate code on the client side?
Server:
import java.net.*;
import java.util.*;
import java.io.*;
public class EchoServer2b extends Thread implements Runnable{
protected static Socket clientSocket;
static String [] logs = new String[100];
//protected static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
static HashMap<String, Socket> clients = new HashMap<String, Socket>();
static int arrayPos = 0;
static int i, clientCount = 0;
static String clientID;
static String receiver="",actualMessage="";
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(10008);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2b (serverSocket.accept());
++clientCount;
clientID = Integer.toString(clientCount);
clients.put(clientID, clientSocket);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally{
try{
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private EchoServer2b (Socket clientSoc){
clientSocket = clientSoc;
start();
}
public void run(){
System.out.println ("New Communication Thread Started");
try{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client ID: " + clientID);
String inputLine;
while ((inputLine = in.readLine()) != null) { //reading
System.out.println(inputLine);
String message[]=inputLine.split(", ");
logs[arrayPos] = message[1]; //keep record of all commands sent to server
arrayPos++; //update array position
receiver=message[0];
actualMessage=message[1];
if (actualMessage.equals("Bye.")) //break if client enters 'Bye."
break;
if(actualMessage.equals("Logs.")){ //print out contents of logs if any client enters 'Logs'
for(i=0; i<arrayPos; i++){
System.out.println("Log"+ i + ": " + logs[i]);
}
break;
}
for (Map.Entry<String, Socket> entry: clients.entrySet()) {
String clientName = entry.getKey();
if(clientName.equals(receiver))
{
Socket socket = entry.getValue();
try {
PrintWriter receiverOut = new PrintWriter(socket.getOutputStream(), true);
//DataOutputStream receiverDOS = new DataOutputStream(socket.getOutputStream());
int x, y, result;
String num1, num2, operator;
String [] splitStrings = actualMessage.split(" ");
num1 = splitStrings[0];
x = Integer.parseInt(num1);
operator = splitStrings[1];
num2 = splitStrings[2];
y = Integer.parseInt(num2);
switch(operator){
case "+":
result = x + y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "-":
result = x - y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "*":
result = x * y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "/":
result = x / y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
default:
System.out.println("Please enter a more simple equation using one of the 4 main operators i.e. '+, -, *, /'");
break;
}
receiverOut.flush();
receiverOut.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
out.flush();
out.close();
in.close();
clientSocket.close();
}
catch (IOException e){
System.err.println("Problem with Communication Server");
e.printStackTrace();
System.exit(1);
}
}
public void sendMessage(String receiver, String actualMessage) {
}
}
Client:
import java.io.*;
import java.net.*;
public class EchoClientB {
static boolean flag = true;
public static void main(String[] args) throws IOException{
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " + serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try{
echoSocket = new Socket(serverHostname, 10008);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}catch (UnknownHostException e){
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e){
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput = "";
System.out.println ("Type Message (\"Bye.\" to quit)");
//System.out.println("Enter a simple math equation i.e. 2 + 2 separated by a space…");
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
while(true){
if(userInput.equals("Bye.")){
break;
}
if((userInput = stdIn.readLine()) != null){
out.println(userInput);
userInput = in.readLine();
System.out.println("echo: " + userInput);
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
out.flush();
}
else if(in.ready()){
userInput = in.readLine();
System.out.println("echo: " + userInput);
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
out.flush();
}
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
In the server run method, at the end of the code where you are sending a message to one of the clients, you have
out.flush();
out.close();
in.close();
clientSocket.close();
}
}
catch (IOException e){
System.err.println("Problem with Communication Server");
System.exit(1);
}
This is closing the socket, and it why you are getting the exception. You may want to move this block to a place where you really do want to close the client's connection
You are getting a IOException because you're closing the stream you're trying to read from at line 140. I suggest you move all the steam closes out of while scope (line 142).
I have a threaded java client/server pair, and it's behaving really strange . Here is the server side :
public class sample_server {
private static int port=4444, maxConnections=0;
// Listen for incoming connections and handle them
public static void main(String[] args) {
int i=0;
try{
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)){
doComms connection;
server = listener.accept();
doComms conn_c = new doComms(server);
Thread t = new Thread(conn_c);
t.start();
}
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private String line,input;
doComms(Socket server) {
this.server=server;
}
public void run () {
input="";
try {
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
PrintStream out = new PrintStream(server.getOutputStream());
while((line = in.readLine()) != null && !line.equals(".")) {
java.util.Date date = new java.util.Date();
String timeString = String.valueOf((date.getTime()));
input=input + line + timeString;
out.println("I got:" + line + " " + timeString + "\n");
}
// Now write to the client
System.out.println("Overall message is:" + input);
out.println("Overall message is:" + input);
server.close();
} catch (IOException ioe) { /* ETC BOILERPLATE */
And this is my client code :
public class sample_client {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
//END OLD CODE
}
}
When I run this code, on the clients it only displays the full "echo" line on every other round, like so :
input: hi
echo: I got:hi 1430872840921
input: ok
echo:
input: hi
echo: I got:ok 1430872842861
input: ok
echo:
input: hi
echo: I got:hi 1430872846214
input: ok
echo:
input:
thanks
PrintStream out = new PrintStream(server.getOutputStream());
You need the autoflush parameter here too, just as in the client where you construct the PrintWriter.
Or else call flush() after every println() in the server, if you can be bothered.
I need a bufferread to work with a client which closes when the word "CLOSE". THE client closes, I just can't get the sever to close once messages have been sent through it.
Heres what code I have:
`
import java.io.*;
import java.net.*;
class TCPClient2 {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser
= new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("143.53.30.136", 49250);//port number and ip address of client
DataOutputStream outToServer
= new DataOutputStream(clientSocket.getOutputStream());
InputStream sin = clientSocket.getInputStream();
// Just converting them to different streams, so that string handling becomes easier.
DataInputStream inFromServer = new DataInputStream(sin);
try {
do {
System.out.print("Enter message : ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
//Question B4
//if statement for closing the socket connection
if (sentence.equals("CLOSE")) {
clientSocket.close();
//closes client socket
System.out.println("Socket Closed");
//prints socket closed to tell user socket has closed
System.exit(0);
}
outToServer.writeBytes(sentence + '\n');
System.out.print("Message sent! please wait for server message: ");
modifiedSentence = inFromServer.readUTF();
System.out.println("FROM SERVER: " + modifiedSentence);
} while (!sentence.equals("CLOSE"));
} catch (IOException e) {
}
clientSocket.close();
}
}`
AND the server:
`
/*
chris and paul
*/
import java.io.*;
import java.net.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TCPMultiThreadServer {
private static ServerSocket welcomeSocket;
//port number the server is using
private static final int PORT = 49250;
private static int clientNo =1;
public static void main(String argv[]) throws Exception
{
System.out.println("Opening port...\n");
try
{
// ServerSocket listens for new connections on specified port
welcomeSocket = new ServerSocket(PORT);
do
{
Socket client = welcomeSocket.accept();
System.out.println("\nNew client accepted.\n");
//Create a thread to handle communication with
//this client and pass the constructor for this
//thread a reference to the relevant socket...
TCPMultiThreadServer.ClientHandler handler =
new TCPMultiThreadServer().new ClientHandler(client,clientNo);
handler.start(); // Calls run() method in ClientHandler
clientNo++;
} while (true);
} catch (IOException e) {}
}
// Original work not credited
class ClientHandler extends Thread
{
private Socket client;
private BufferedReader inFromClient;
private BufferedReader text_to_Client;
private DataOutputStream outToClient;
private FileWriter Filestream;
private BufferedWriter out;
public int clientNo;
public boolean stopping;
//part A question 4, adding buffer string array to the program
private String[] buffer; //creation of buffer string array.
private int bufferI; // Index of the last thing inserted into the array
public ClientHandler(Socket socket, int clientNos)
{
//Set up reference to associated socket
client = socket;
clientNo= clientNos;
try
{
// Gets access to input/output stream of socket
inFromClient =
new BufferedReader(new InputStreamReader
(client.getInputStream()));
text_to_Client =
new BufferedReader(new InputStreamReader(System.in));
outToClient =
new DataOutputStream(client.getOutputStream());
} catch(IOException e) {}
}
public void run()
{
try
{
stopping = false;
//Question A4 buffer continued
buffer = new String[4];
//generates buffer string array containing 4 strings
bufferI = 0;
// make sure bufferIndex = 0
String clientSentence;
Thread mythread = Thread.currentThread();
do
{
//Accept message from client on socket's input stream
OutputStream sout = client.getOutputStream();
// Just converting them to different streams, so that string
// handling becomes easier.
DataOutputStream text_to_send = new DataOutputStream(sout);
clientSentence = inFromClient.readLine();
System.out.println("Message received from client number " +
clientNo + ": "+ clientSentence);
// String to be scanned to find the pattern.
String line = clientSentence;
String pattern = "[C][L][O][S][E]";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
//if (m.find( )) {
// System.out.println("Found value: " + m.find() );
// System.out.println("Found value: " + m.group(1) );
//System.out.println("Found value: " + m.group(2) );
//} else {
// System.out.println("NO MATCH");
//}
//part B question 4 close command
//if statement for closing the socket connection if it is equal to close
if(m.matches())
{ //prints socket closed to tell user socket has closed
System.out.println("Socket connection to client number "
+ clientNo + " closed");
try
{
} catch(Exception e) {}
out.flush();
out.close(); // Close the file handler
client.close(); // Close the connection with the client,
clientNo--; // Decrement the number of clients
}
else
{
//part A question 4, adding buffer string array to the program
// looks to see if the buffer string array is full
//and also looks to see if bufferIndex is in range
if (bufferI > buffer.length-1)
{
// Print BUFFER FULL
System.out.println("BUFFER FULL");
// Clear clientSentence string
clientSentence = " ";
// For loop which travels through the buffer array of string
for (int i=0; i<buffer.length; i++)
{
// Append buffer element to clientSentence string
clientSentence += buffer[i] + " , ";
buffer[i] = null; // makes the buffer null
}
bufferI = 0; // Reset bufferI back to 0 so writing to the buffer can restarted
// prints buffer cleared back to the clients
text_to_send.writeUTF("BUFFER CLEARED :" +
clientSentence);
}
else
{
buffer[bufferI] = clientSentence;
System.out.println("Buffer " + bufferI+ ": " +
buffer[bufferI]);
bufferI++;
System.out.println("Enter Message: ");
// Reads message from server interface
// and sends it to the client
clientSentence = text_to_Client.readLine();
text_to_send.writeUTF(clientSentence);
System.out.println("Your message: " +
clientSentence);
}
}
if (mythread.activeCount() == 2 &&
(clientNo ==0 || clientNo >0) &&
clientSentence.equals("CLOSE"))
{
System.exit(0);
}
} while(!clientSentence.equals("CLOSE"));
client.close();
} catch(IOException e) {}
}
}
}
`
I am trying to get whole txt file range by range which is specificly determined. 1st request is successfully completed but when I do second get request to receive the second part, I couldn't get any response, just nulls. Is there a lack of something? I put a while loop to observe if any value will come after nulls, but I couldn't see!
I don't use any special library for this http socket. I just create a socket with port 80 and a bufferedwriter(writer) and bufferedreader(reader) to communicate with server.
This is the whole method. I have updated the question:
public static void rangedRequest(String host, String url, int totalPartNum, String outputFile) throws IOException{
String headRequest = "HEAD " +url+" HTTP/1.1\r\n"
+ "Host: "+ host +"\r\n\r\n";
Socket sock = null;
BufferedWriter writer = null;
BufferedReader reader = null;
try {
sock = new Socket(host, 80);
writer= new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
reader= new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (UnknownHostException ex) {
System.out.println("ERROR:Unknown host");
System.exit(0);
}
writer.write(headRequest);
writer.flush();
/***************Response**************/
String response;
int totalLength = 0;
do{
response = reader.readLine();
if(response.indexOf("Content-Length") > -1){
totalLength = Integer.parseInt(response.substring(response.indexOf(' ')+1));
response = null;
}
}while(response != null);
/****File Length infor is received****/
BufferedWriter output = new BufferedWriter(new FileWriter(outputFile));
int range = totalLength/totalPartNum;
for (int i = 0; i < totalPartNum; i++) {
String getRequest = "GET " + url + " HTTP/1.1\r\n" +
"Host: "+ host + "\r\n" +
"Range: bytes="+ i*range + "-" + ((i+1)*range -1) +
"\r\n\r\n"; //get range query
writer.write(getRequest);
writer.flush();
boolean afterInfo = false;
while(!reader.ready()){}
do{
response = reader.readLine();
if(response.indexOf("Range")>-1){ //After some information, there is an empty line and data
afterInfo = true; //To understand info part is reached
}
}while(!(response.length() < 1 && afterInfo));
while(response != null){
output.write(response);
response = reader.readLine();
}
}
sock.close();
}
Create new socket, each time you are sending a new request to the Http server. So that you need to reconstruct sock, writer and reader then do the request to the Http server and finally close the socket and shutdown its input and output streams in the loop.