I'm writing a simple multi threaded java proxy, but I can't seem to get the server to display what I said, or send anything back. Here is my code:
import java.io.*;
import java.net.*;
public class TcpClient {
public static void clientS( int portNumber, String request) throws Exception {
String sentence = "";
String modifiedSentence = "";
System.out.println("In client class..");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", portNumber);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeUTF(modifiedSentence);
System.out.println("What got written to the server: "+request);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
clientSocket.close();
//TcpServerThread tcpThread = new TcpServerThread(clientSocket);
//tcpThread.run();
}//end method
}// client class
import java.net.Socket;
import java.util.Scanner;
import java.util.StringTokenizer;
public class RequestParser extends TcpServerThread{
static String method = "";
static String endUrl = "";
static String version = "";
static String hostHeader = "";
static String host = "";
static String hostHeader1 = "";
static String host1 = "";
static String hostHeader2 = "";
static String host2 = "";
public RequestParser(Socket theSocket) {
super(theSocket);
}
static int portNumber = 80;
public int Request() {
Scanner scan = new Scanner(System.in);
System.out.println("Please type in your information, with headers separated by a space: ");
String request = scan.nextLine();//stores the HTTP request
//parses the HTTP request, gets port number if there is one
try {
portNumber = doFormattedMethodRequest(request);
TcpClient.clientS(portNumber, request);
} catch (Exception e) {
e.getMessage();
}
return portNumber;
}//end method
public static int doFormattedMethodRequest(String unformattedRequest) throws Exception{
System.out.println("In String Parser...");
StringTokenizer tokenizer = new StringTokenizer(unformattedRequest," ");
Scanner scan = new Scanner(System.in);
//gets method, loops if there isn't correct input
while (tokenizer.hasMoreElements()){
method = (String) tokenizer.nextElement();
System.out.println("method: "+method);
if (!method.equals("GET")){
System.out.println("This program only supports GET requests");
System.out.println("Your method has been changed to GET");
method = "GET";
}//end if
endUrl = (String) tokenizer.nextElement();
System.out.println("endUrl: "+endUrl);
if(!endUrl.endsWith(".html")|| !endUrl.endsWith(".com")
|| !endUrl.endsWith(".edu")||!endUrl.endsWith(".gov")||
!endUrl.endsWith(".net")||!endUrl.endsWith(".org")||
!endUrl.endsWith(".mil")){
String [] parts = endUrl.split("/");
for (int i=0;i<parts.length;i++){
host = "www."+parts[2];
if (parts[i].matches("/*[1-65535].*") == true){
String port = parts[i];
portNumber = Integer.parseInt(port);
System.out.println("Contains a port number");
System.out.println("Port Number is: "+portNumber);
}//end if
}//end for loop
}//end if
version = (String) tokenizer.nextElement();
System.out.println("version: "+version);
if (!version.endsWith("1.0")){
System.out.println("This program only supports version of 1.0");
System.out.println("Your version has been changed to 1.0");
version = "1.0";
}
System.out.println("host: "+host);
hostHeader = (String) tokenizer.nextElement();
host = (String) tokenizer.nextElement();
hostHeader1 = (String) tokenizer.nextElement();
host1 = (String) tokenizer.nextElement();
hostHeader2 = (String) tokenizer.nextElement();
host2 = (String) tokenizer.nextElement();
}//end while loop
System.out.println("OK, here is what is being sent to the server...");
System.out.print(method); System.out.print(" "+endUrl);
System.out.println(" "+version);
//System.out.print(hostHeader); System.out.println(host+endUrl);
//System.out.print(hostHeader1); System.out.print(host);
//System.out.println(hostHeader);System.out.println(host);
return portNumber;
}//end method
}//end class
import java.io.*;
import java.net.*;
class TcpServerThread extends Thread{
static Socket connectionSocket = null;
static int portNumber = 0;
public TcpServerThread(Socket theSocket){
super("TcpServerThread");
TcpServerThread.connectionSocket = theSocket;
}
public static void main(String args[]) {
System.out.println("Taking you to HTTP request input...");
RequestParser estProxy = new RequestParser(connectionSocket);
portNumber = estProxy.Request();//goes to get the user's http request
System.out.println("");
System.out.println("-----------------------------------------------------");
System.out.println("System returned "+portNumber+" as the port number.");
//create listener socket to listen for requests
ServerSocket welcomeSocket;
try {
welcomeSocket = new ServerSocket(portNumber);
System.out.println("");
System.out.println("Listening on port number "+portNumber+"...");
estProxy.run();
boolean isListening = true;
while (isListening) {
new TcpServerThread(welcomeSocket.accept()).start();
}//end while
} catch (Exception e) {
e.getMessage();
}
}//end method
public void run(){
System.out.println("Got into run method");
Socket serverSocket = new Socket();
Socket clientSocket = new Socket();
try{
InputStream inStream = clientSocket.getInputStream();
byte [] buf = new byte[9000];
int length = inStream.read(buf);
System.out.println(new String(buf,0,length));
Socket socket= new Socket("localhost",portNumber);
OutputStream outStream = socket.getOutputStream();
outStream.write(buf,0,length);
OutputStream inStream1 = clientSocket.getOutputStream();
InputStream outStream1 = socket.getInputStream();
for(int length1; (length1 = outStream1.read(buf)) != -1;){
inStream1.write(buf,0,length1);
}
inStream1.close();
outStream1.close();
outStream.close();
inStream.close();
socket.close();
}
catch(Exception e){
e.getMessage();
}
finally{
try{
clientSocket.close();
}
catch(IOException e){
e.getMessage();
}
}
}//end method
}
Most of my communication with the server is happening in the TcpServerThread class, and I'm trying to use the TcpClient class to talk to the server, send an HTTP request, and print out what the server sends back, although after I input an http request, it only parses it and then just goes blank. Any help would be much appreciated.
You're calling writeUTF() but nobody is calling readUTF(). That's the only way anyone will understand what is written.
Howver this proxy won't work. Once you've created the initial connections you need two threads per connection, one to read and write in each direction. You can't assume that the request or response are read in a single read, and you can't generally assume that there is a single request/response pair, or indeed anything like a request or response at all.
Related
I am trying to create a text messaging program with three files (main function file, client file, server file) where text messages can be sent and received at the same time, multiple times (ability to send multiple messages by pressing enter after each message, ability to receive multiple messages after connection after the other side presses enter after each message)
There are four threads (one thread for receiving messages on server, one thread for sending messages on server, one thread for receiving messages on client, one thread for sending messages on client)
If "-l" is present on the command line, it will run as a server, otherwise it will run as a client
Command line arguments to run server:
java DirectMessengerCombined -l 3000
Command line arguments to run client:
java DirectMessengerCombined 3000
The command line arguments (String[] args) should be accessible to all 3 files.
Here is the code where the threads are created:
Code of main function file:
import java.io.IOException;
public class DirectMessengerCombined implements Runnable
{
public static void main(String[] args) throws IOException
{
DirectMessengerClient client1 = null;
DirectMessengerServer server1 = null;
Thread ServerRead = new Thread ();
Thread ServerWrite = new Thread ();
Thread ClientRead = new Thread ();
Thread ClientWrite = new Thread ();
for (int i = 0; i < args.length; i++)
{
if (args.length == 1)
{
client1 = new DirectMessengerClient(args);
client1.ClientRun(args);
ClientRead.start();
ClientWrite.start();
}
else if (args.length == 2)
{
server1 = new DirectMessengerServer(args);
server1.ServerRun(args);
ServerRead.start();
ServerWrite.start();
}
i=args.length + 20;
}
}
#Override
public void run()
{
//This method is just to get rid of the "implements" error
//There are four threads, so which one is accessing this method??
}
}
In the following code there are comments such as "//I would like this to be the ServerRead thread method". I would like to know how to make that comment viable or put it into real code somehow to make it work with the corresponding threads in the main function file
Code of Server file:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class DirectMessengerServer implements Runnable
{
private String[] serverArgs;
private static Socket socket;
public boolean keepRunning = true;
int ConnectOnce = 0;
public DirectMessengerServer(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
run();
}
public String[] ServerRun(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
return serverArgs;
}
//I would like this to be the ServerRead thread method
public void run()
{
try
{
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
}
while(keepRunning)
{
//Reading the message from the client
//BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClient = br.readLine();
System.out.println("Message received from client: "+ MessageFromClient);
// ServerSend.start();
runSend();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
//I would like this to be the ServerWrite thread method
public void runSend()
{
while(keepRunning)
{
System.out.println("Server sending thread is now running");
try
{
//Send the message to the server
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
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
ConnectOnce = 4;
// run();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
}
}
Client file code:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
private String[] clientArgs;
private static Socket socket;
public boolean keepRunning = true;
public DirectMessengerClient(String[] args) throws IOException
{
// set the instance variable
this.clientArgs = args;
run(args);
}
public String[] ClientRun(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
return clientArgs;
}
//I would like this to be the ServerWrite thread method
public void run(String args[]) throws IOException
{
System.out.println("Client send thread is now running");
while(keepRunning)
{
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
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
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
runClientRead(args);
}
}
//I would like this to be the ClientRead thread method
public void runClientRead(String args[]) throws IOException
{
System.out.println("Client recieve/read thread is now running");
//Integer port= Integer.valueOf(args[0]);
//String host = "localhost";
//InetAddress address = InetAddress.getByName(host);
//socket = new Socket(address, port);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
}
}
My question is how to make those methods work with the threads inside the main function file and/or how to turn the comments into real code for the corresponding threads in the main file?
EDIT: I am able to get it to send one message at a time successfully now, is there a way to make it so I can send and receive multiple messages at a time?
I am trying to create a text messaging program with three files (main function file, client file, server file)
If "-l" is present on the command line, it will run as a server, otherwise it will run as a client
Command line arguments to run server:
java DirectMessengerCombined -l 3000
Command line arguments to run client:
java DirectMessengerCombined 3000
All three files need to be able to access String args[] in the main function file because that is how it gets the port number
Screenshot of error (Server on left, client on right):
The problem with this screenshot is that the "how are you" message is never received by the server (left window)
Code of Server file (DirectMessengerServer):
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class DirectMessengerServer
{
private String[] serverArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
int ConnectOnce = 0;
public DirectMessengerServer(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
run();
}
public String[] ServerRun(String[] args) throws IOException
{
//How do I get the String[] args in this method be able to access it in the run methods?
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
return serverArgs;
}
Thread ListeningLoop = new Thread();
//run method of ServerRecieve
public void run() throws IOException
{
try
{
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
}
while(keepRunning)
{
//Reading the message from the client
//BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClient = br.readLine();
System.out.println("Message received from client: "+ MessageFromClient);
// ServerSend.start();
runSend();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
Thread ServerSend = new Thread ();
//Run method of ServerSend
public void runSend()
{
while(keepRunning)
{
System.out.println("Server sending thread is now running");
try
{
//Send the message to the server
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
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
run();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
}
}
Code of client (DirectMessengerClient):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
private String[] clientArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
public DirectMessengerClient(String[] args) throws IOException
{
// set the instance variable
this.clientArgs = args;
run(args);
}
public String[] ClientRun(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
return clientArgs;
}
Thread ClientSend = new Thread();
public void run(String args[]) throws IOException
{
System.out.println("Client send thread is now running");
while(keepRunning)
{
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
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
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
runClientRead(args);
}
}
Thread ClientRead = new Thread();
public void runClientRead(String args[]) throws IOException
{
System.out.println("Client recieve/read thread is now running");
//Integer port= Integer.valueOf(args[0]);
//String host = "localhost";
//InetAddress address = InetAddress.getByName(host);
//socket = new Socket(address, port);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
}
}
Code of main function file (DirectMessengerCombined):
import java.io.IOException;
public class DirectMessengerCombined
{
public static void main(String[] args) throws IOException
{
DirectMessengerClient client1 = null;
DirectMessengerServer server1 = null;
for (int i = 0; i < args.length; i++)
{
if (args.length == 1)
{
client1 = new DirectMessengerClient(args);
client1.ClientRun(args);
}
else if (args.length == 2)
{
server1 = new DirectMessengerServer(args);
server1.ServerRun(args);
}
i=args.length + 20;
}
}
}
My question is: Why is the server able to accept the first message but not able to accept the second message ("how are you")?
I'm creating two program files (one client one server).
Each file has one thread (one thread for server, one thread for client)
At runtime, there is supposed to be only one server, and there is supposed to be multiple and/or potentially infinite number of clients connecting to the server at the same time)
In order to get multiple clients to run, the user opens multiple command prompt / mac terminal windows (each window being one client) (one window being the server, so it requires at least two windows to run)
Once a client is connected, it can send messages (utf-8 strings) to the server. It will also receive from the server all messages sent from the other connected clients (it will not receive messages sent from itself).
Screenshot of exception in thread / array index out of bounds error (eclipse):
Screenshot of Socket Exception error (server):
Screenshot of error on client side:
Code of Server (ChatServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
ChatServer chatserver = new 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);
socket = serverSocket.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//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
{
static int numberOfClients = 0;
public static void main(String args[])
{
ChatClient chatclient = new ChatClient();
//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 );
boolean KeepRunning = true;
while(KeepRunning)
{
for(int i = 0; i < numberOfClients; i++)
{
System.out.println(messagessentbyotherclients);
}
try
{
Socket clientSocket = new Socket("localhost", port);
InetAddress inetlocalhost = InetAddress.getByName("localhost");
SocketAddress localhost = new InetSocketAddress(inetlocalhost, port);
clientSocket.connect(localhost, port);
System.out.println("Client has connected");
//client creates new message from standard input
OutputStream os = clientSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
}
catch (IOException e)
{
e.printStackTrace();
}
//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;
try
{
Socket clientSocket = new Socket("localhost", port);
SocketAddress localhost = null;
clientSocket.connect(localhost, port);
OutputStream os = clientSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(sendMessage + "\n");
bw.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("Message sent to server: "+sendMessage);
}
}
finally
{
}
}
};
ChatClient1.start();
}
}
}
My question is: How should I go about resolving all three errors (it seems like if I change one part of the code, then the other errors will either still exist or be resolved due to that but I could be wrong)? I would also like to know if there's a way to list the number of clients in an arraylist in the server code so that when a client closes their window I can keep the server up by just removing them from the list.
Have a task to create a basic http server. I've gotten to the point where it asks you to send text response back that should be displayed in your browser if you go to http://localhost:8080/ but I just get a page cannot be displayed error. I think it must be something to do with the format of the response I'm sending but i just can't get it. Any help would be much appreciated.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpServer{
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(8080);
while(true){
HttpServerSession sesh = new HttpServerSession(ss.accept());
sesh.start();
}
}catch(IOException e){
System.err.println("IOException");
}
}
}
class HttpServerSession extends Thread {
private Socket client;
public HttpServerSession(Socket client){
this.client = client;
}
private void println(BufferedOutputStream bos, String s) throws IOException {
String news = s + "\r\n";
byte[] array = news.getBytes();
for(int i = 0; i < array.length; i++){
bos.write(array[i]);
}
return;
}
public void run(){
try{
InetAddress clientIP = client.getInetAddress();
System.out.println("We just got a message! " + clientIP.getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String request = reader.readLine();
System.out.println(request);
String[] parts = request.split(" ");
if(parts.length == 3){
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
String filename = parts[1].substring(1);
if(parts[0].equals("GET")){
while(true){
String line = reader.readLine();
System.out.println(line);
if(line == null || line.equals("")){
break;
}
}
println(bos, "OK");
println(bos, "");
println(bos, "Hello World");
}
}
client.close();
}catch(Exception e){
System.err.println("Exception in thread");
}
}
}
Turns out I just had to flush the BufferedOutputStream
I'm trying to check whether several pors are open and if 80 port is open - send http request and then show result in console. Every port is checked in his own thread.
I send requests like this
public static void send(Socket sock, String host) throws IOException{
PrintWriter pw = new PrintWriter(sock.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: " + host);
pw.println("");
pw.flush();
}
In class TCPClient I use it and return result as bytes and then show it console.
try {
sock = new Socket(host, port);
System.out.println("port " + port + " is in use");
// send request
HttpSender.send(sock, host);
BufferedReader bf = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuffer response = new StringBuffer();
String line = "";
while((line = bf.readLine()) != null) {
response.append(line);
response.append('\r');
}
bf.close();
return String.valueOf(response).getBytes(); // in method run I show it
} catch (SocketException e) {
return ("port " + port + " is free").getBytes();
}
I create pool of threads for port checking.
public class ThreadPool {
private static int MAX_THREADS = 5;
private static String DESTINATION = "http://stackoverflow.com/";
private ExecutorService es = null;
public ThreadPool() {
es = Executors.newFixedThreadPool(MAX_THREADS);
}
public void perform(int start, int end) throws UnknownHostException {
for (int i = start; i <= end; i++) {
Runnable req = new TCPClient(DESTINATION, i);
es.execute(req);
}
es.shutdown();
while (!es.isTerminated()) {
}
;
System.out.println("all ports checked!");
}
}
When I set destination as www.stackoverflow.com and got document with text that it was moved permanently to http://stackoverflow.com/. When I set this destination - I've got UnknownhostException.
Where is the problem?
Have you tried private static String DESTINATION = "stackoverflow.com";? The string "http://stackoverflow.com" isn't a hostname, it's a URL.